I am attempting to unit test 2 exported helper functions that both call useContext
on my default context value, however I can’t seem to get it working after a lot of looking online.
export const func1 = () => {
const { key1, key2 } = useContext(MyContext);
return { key1, key2 };
}
export const func2 = () => {
const { key2 } = useContext(MyContext);
// some more complex stuff here
}
Test
import React, { useContext } from 'react';
...
it('with mock', () => {
jest.mock('react', () => ({
...jest.requireActual('react'),
useContext: (ctx: any) => mockUseContext(ctx)
}));
useContext.mockImplementation(ctx => ({ someKey: 'someVal' }));
// Property 'mockImplementation' does not exist on type ' (context: Context ) => T
expect(func1()).toBe({ someKey: 'someVal' });
});
it('with spyOn', () => {
jest.spyOn(React, 'useContext').mockImplementation(() => ({ someKey: 'someVal' }));
expect(func1()).toBe({ someKey: 'someVal' });
});
2
Answers
When unit testing helper functions that use the
useContext
hook, you need to mock theuseContext
function to provide your own mock values. Here’s how you can do it:In this example, we use
jest.mock
to mock theuseContext
function from React. Then, we set the return value of theuseContext
mock tomockContextValue
, which is an object representing the values you want to use in your tests.Inside each test, we import the specific function being tested and call it. In the case of
func1
, we expect the result to be equal tomockContextValue
.Note that in order to make the mocking work correctly, you need to make sure you import the functions inside each test case, as shown in the example. This ensures that the mocked version of
useContext
is used when calling the function.Feel free to modify the code as per your needs and add additional assertions and test cases for
func2
or any other helper functions you want to test.See jest.Mocked
"jest": "^26.6.3"