I have a component that uses useContext
and then its output is dependent on the value in the context. A simple example:
import React, { useConte
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:
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');
});
This is a bit dirty, though, and implementation-specific, so if you're able to compromise on the use of the shallow renderer, there's a few other options available:
If you're not shallow rendering, you can just wrap the component in a context provider to inject the value you want:
import TestRenderer from 'react-test-renderer';
test("non-shallow render", () => {
const element = new TestRenderer.create(
<NameContext.Provider value="Provided Value">
<MyComponent />
</NameContext.Provider>
);
expect(element.root.findByType("div").children).toEqual(['Provided Value']);
});
(Disclaimer: this should work, but when I test it, I'm hitting an error which I think is an issue in my setup)
As @skyboyer commented, enzyme's shallow renderer supports .dive
allowing you to deeply renderer a part of an otherwise shallow rendered component:
import { shallow } from "./enzyme";
test("enzyme dive", () => {
const TestComponent = () => (
<NameContext.Provider value="Provided Value">
<MyComponent />
</NameContext.Provider>
);
const element = shallow(<TestComponent />);
expect(element.find(MyComponent).dive().text()).toBe("Provided Value");
});
Finally, the Hooks FAQ has an example of testing hooks with ReactDOM
, which works as well. Naturally, using ReactDOM
means this is also a deep render, not shallow.
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
test("with ReactDOM", () => {
act(() => {
ReactDOM.render((
<NameContext.Provider value="Provided Value">
<MyComponent />
</NameContext.Provider>
), container);
});
expect(container.textContent).toBe("Provided Value");
});
What I did is test if useContext
was used. In my case, useContext
returns function called dispatch
.
In the component I have:
const dispatch = useContext(...);
and then inside onChange
method:
dispatch({ type: 'edit', payload: { value: e.target.value, name: e.target.name } });
So inside test at the begining:
const dispatch = jest.fn();
React.useContext = (() => dispatch) as <T>(context: React.Context<T>) => T;
and then:
it('calls function when change address input', () => {
const input = component.find('[name="address"]');
input.simulate('change', { target: { value: '123', name: 'address' } });
expect(dispatch).toHaveBeenCalledTimes(1);
});
Old post but if it helps someone this is how I got it to work
import * as React from 'react';
import { shallow } from 'enzyme';
describe('MyComponent', () => {
it('should useContext mock and shallow render a div tag', () => {
jest.spyOn(React, 'useContext').mockImplementation(() => ({
name: 'this is a mock context return value'
}));
const myComponent = shallow(
<MyComponent
props={props}
/>).dive();
expect(myComponent).toMatchSnapShot();
});
});
To complete the above accepted answer, for non-shallow rendering, I slightly tweaked the code to simply surround my component with the context
import { mount } from 'enzyme';
import NameContext from './NameContext';
test("non-shallow render", () => {
const dummyValue = {
name: 'abcd',
customizeName: jest.fn(),
...
};
const wrapper = mount(
<NameContext.Provider value={dummyValue}>
<MyComponent />
</NameContext.Provider>
);
// then use
wrapper.find('...').simulate('change', ...);
...
expect(wrapper.find('...')).to...;
});
I tried to use Enzyme + .dive
, but when diving, it does not recognize the context props, it gets the default ones. Actually, it is a known issue by the Enzyme team.
Meanwhile, I came up with a simpler solution which consists in creating a custom hook just to return useContext
with your context and mocking the return of this custom hook on the test:
AppContext.js - Creates the context.
import React, { useContext } from 'react';
export const useAppContext = () => useContext(AppContext);
const defaultValues = { color: 'green' };
const AppContext = React.createContext(defaultValues);
export default AppContext;
App.js — Providing the context
import React from 'react';
import AppContext from './AppContext';
import Hello from './Hello';
export default function App() {
return (
<AppContext.Provider value={{ color: 'red' }}>
<Hello />
</AppContext.Provider>
);
}
Hello.js - Consuming the context
import React from 'react';
import { useAppContext } from './AppContext';
const Hello = props => {
const { color } = useAppContext();
return <h1 style={{ color: color }}>Hello {color}!</h1>;
};
export default Hello;
Hello.test.js - Testing the useContext with Enzyme shallow
import React from 'react';
import { shallow } from 'enzyme';
import * as AppContext from './AppContext';
import Hello from './Hello';
describe('<Hello />', () => {
test('it should mock the context', () => {
const contextValues = { color: 'orange' };
jest
.spyOn(AppContext, 'useAppContext')
.mockImplementation(() => contextValues);
const wrapper = shallow(<Hello />);
const h1 = wrapper.find('h1');
expect(h1.text()).toBe('Hello orange!');
});
});
Check the full Medium article out https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83
Or if you're testing your component in isolation without mounting the parent components you can simply mocking useContext:
jest.mock('react', () => {
const ActualReact = require.requireActual('react')
return {
...ActualReact,
useContext: () => ({ }), // what you want to return when useContext get fired goes here
}
})
You can still use a dynamic useContext
value with a global jest.fn