This gist aim's to gethering some leasons learned by testing React hooks with Jest and TypeScript.
Last active
July 17, 2020 07:14
-
-
Save marco-souza/d5243bd1ff1925176c5e1062f9bfd8fe to your computer and use it in GitHub Desktop.
React Testing Cookbook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import react at the top | |
import React from 'react'; | |
describe('OverviewPage', () => { | |
// to mock useEffect | |
const useEffectSpy = jest.spyOn(React, 'useEffect'); | |
beforeEach(() => { | |
useEffectSpy.mockImplementation(() => {}); | |
}); | |
// to mock useState | |
const useStateSpy = jest.spyOn(React, 'useState'); | |
const setStateMock = jest.fn(); | |
beforeEach(() => { | |
useStateSpy.mockImplementation(() => [false, setStateMock]); | |
}); | |
// continue... | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you need to use the useEffect callback function to execute it, you can do | |
it('my test', () => { | |
// ... | |
// get and exec useEffect Handler | |
const useEffectHandler = useEffectSpy.mock.calls[0][0]; | |
useEffectHandler(); | |
// ... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment