Reputation: 51
Let's say I have this functional React component.
const SomeComponent = ({ onShow }) => {
React.useEffect(onShow, []);
return <div />;
};
Now I want to unit test that SomeComponent
calls onShow the first time it is rendered.
Is that possible using enzyme
?
I have tried implementing two very similar tests, the difference being that the first is using enzyme, the other one using react-testing-library.
The test that uses react-testing-library passes, but the enzyme test fails, even though they test the same code.
Example:
import * as reactTestingLibrary from "react-testing-library";
import * as React from "react";
import * as enzyme from "enzyme";
const SomeComponent = ({ onShow }) => {
React.useEffect(onShow, []);
return <div />;
};
describe("Testing useEffect with enzyme", () => {
it("calls the side effect", async () => {
const aFn = jest.fn();
enzyme.mount(<SomeComponent onShow={aFn} />);
expect(aFn).toHaveBeenCalledTimes(1); // this test fails
});
});
describe("Testing useEffect with react-testing-library", () => {
it("calls the side effect", async () => {
const aFn = jest.fn();
reactTestingLibrary.render(<SomeComponent onShow={aFn} />);
expect(aFn).toHaveBeenCalledTimes(1); // this test passes
});
});
Is there a way to make enzyme execute the hook and pass the test?
Upvotes: 3
Views: 3738
Reputation: 11
i just upgraded my enzyme-adapter-react-16 to v1.12.1, that sorted it out for me.
Upvotes: 1
Reputation: 51
Yes, it is possible to test components that uses hooks, using enzyme.
Upgrading enzyme-adapter-react-16 to latest version (1.12.1) fixed the problem.
Upvotes: 1