jeudi 13 août 2020

testing if a window function has been called within a hook

I have a function I need to mock within a react hook: window.analytics.identify and test if its been called

function useNiceHook(data) {
  useEffect(() => {
    ...
      window.analytics.identify(
        ...
  }, [data])
}

export { useNiceHook }

I am trying to mock this like so

windowSpy.mockImplementation(() => ({
        analytics: {
          identify: jest.fn(),
        },
      }))

and then test:

renderHook(() => useNiceHook(data))

      expect(window.analytics.identify).toBeCalled()

But I'm currently getting a failed test:

Error: expect(jest.fn()).toBeCalled()

Expected number of calls: >= 1
Received number of calls:    0

Aucun commentaire:

Enregistrer un commentaire