I've been teaching myself how to test react components with enzyme
and jest
, but I'm clueless as to how to test a mounted component which uses React hooks.
Here is a simplified version of the component...
const [records, setRecords] = useState([]);
const onChange = async ({ value }) => {
try {
const request = await searchRecords();
console.log("Before setRecords");
setRecords(request.results);
console.log("After setRecords");
} catch (error) { /* error handling */ }
}
The test code looks like...
let wrapped;
describe("Sample", () => {
beforeEach(() => {
jest.clearAllMocks();
wrapped = mount(
<Provider store={createStore(reducers, {})}>
<Sample />
</Provider>
);
api.mockImplementation(() => ({ results: searchResult }));
});
afterEach(() => {
wrapped.unmount();
});
it("shows items in the search box", () => {
wrapped.find("#searchField")
.simulate("change", { target: { value: "blah blah" } });
// This triggers "onChange" function
wrapped.update();
expect(wrapped.find("li").length).toEqual(10);
// If "setRecords()" hook works, there will be 10 "li" elements
});
});
The test itself passes, but I see the following message in CLI.
Warning: An update to SearchBox inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
Following the link provided in the warning message, I surrounded the lines which updated the state.
i.e.
act(() => {
wrapped.find("#searchField").simulate("change", { target: { value: "red" } });
});
Still, the warning message persists. Just in case, I surrounded the mount(...)
part, but it doesn't change anything.
In the test examples on React's doc, enzyme
isn't used, so I feel like React Hooks
are not compatible with enzyme
.
How can we remove the warning message while still using enzyme
? Or, is enzyme
really incompatible?
Any advice will be appreciated.