4

I have the following files in a React app with Vitest (which has the same API as Jest):

// hooks/useEntities/useEntities.ts

return useEntities() {
    // this hooks send api requests so I will mock it in the test file.
}
// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'

function SomeComponent () {
    const entities = useEntities()

    return <div>...</div>
}
// SomeComponent.test.tsx

vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
    default: [...]
}))

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}

Because I mock a lot of hooks this way. I want to separate the mocking part to a different file, so it can be reused. I've tried to following ways without a success:

// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))
// SomeComponent.test.tsx => this mocking seems to work

await init()

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}

also tried this way:

// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))
// SomeComponent.test.tsx => this mocking seems to work

describe(...) {
    beforeAll(async () => {
        await init()
        await init(vi) // tried the same thing with passing the vi instance to the init function in the separate file
    })
    it(...) {
        render(<SomeComponent />)
    }
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Matan Gubkin
  • 3,019
  • 6
  • 25
  • 44
  • Have you tried creating another `__mocks__` folder? - https://jestjs.io/docs/manual-mocks - https://vitest.dev/guide/mocking.html#automocking-algorithm – jchua Feb 21 '23 at 03:03
  • yes and it didn't work @jchua – Matan Gubkin Feb 25 '23 at 09:14
  • do you happen to be using any Mock Service Workers? As MSWs could be intercepting your mocked data within each test. – jchua Feb 25 '23 at 09:46

0 Answers0