waitFor running a false positive for mocked function

  Kiến thức lập trình

I have a React/TypeScript project that I’m using mobx-state-tree for state management. In one of my tests (using Vitest + React Testing Library), I mocked a function defined in one of the stores in the state tree, so I can test for its call (it should get called in a useEffect on mount).

Sample code:

// all imports

export const SampleComponentPage = () => {
  ....

  useEffect(() => {
    // the action from the store gets called here (lets call it get_sample()
  }, [])

  return (
    ...
  )
})

Test file:

...

describe('Sample component page', () => {
  it('sample test case', async () => {
    const mock_action = vi.fn()
    const initialStore = // root store with all stores including the store where get_sample has been set to mock_action

    render(
      <StoreContextProvider value={initialStore}>
        <SampleComponentPage />
      </StoreContextProvider>
    )

    ...
    waitFor(() => expect(mock_action).toHaveBeenCalled())
    ...
  })
})

However, the waitFor is returning a false positive test – the test passes regardless e.g with toHaveBeenCalledTimes(10) even though it should only have been called once.

Without the waitFor, it returns an error related to the spy function

AssertionError: expected "spy" to be called once, but got 0 times

I’ve tried using vi.spyOn but that doesn’t work either (+ I want to usevi.fn()).

What’s the best fix for this?

LEAVE A COMMENT