If you want to test a react component that is dependent on useContext hook? In general, using hooks shouldn’t change testing strategy much. The bigger issue here actually isn’t the hook, but the use of context, which complicates things a bit.
There’s a number of ways to make this work, but only approach I’ve found that works with ‘react-test-renderer/shallow’ is to inject a mock hook:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import ShallowRenderer from 'react-test-renderer/shallow'; let realUseContext; let useContextMock; // Setup mock beforeEach(() => { realUseContext = React.useContext; useContextMock = React.useContext = jest.fn(); }); // Cleanup mock afterEach(() => { React.useContext = realUseContext; }); test("mock hook", () => { useContextMock.mockReturnValue("Test Value"); const element = new ShallowRenderer().render( <MyComponent /> ); expect(element.props.children).toBe('Test Value'); }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.