3

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?

5
  • Can you update your libraries. For me both of the tests are working --> "react": "^16.8.6", "enzyme": "^3.9.0", "react-testing-library": "^7.0.0", , "react-test-renderer": "^16.8.6", Commented May 10, 2019 at 12:32
  • @tarzenchugh I had the latest versions in your list but I had missed to upgrade the enzyme adapter. Upgrading enzyme-adapter-react-16 to 1.12.1 fixed my problem. Thank you so much! Commented May 10, 2019 at 13:35
  • Your welcome; Welcome to stack overflow :) Commented May 10, 2019 at 13:36
  • please create answer and mark it as a solution; I believe there may be other people running into that and having solution in comments makes that harder to realize Commented May 11, 2019 at 14:17
  • toHaveBeenCalled is a horrible test to begin with. You're not testing any kind of behavior our output and you're reaching into the details of your component Commented Oct 7, 2020 at 1:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

i just upgraded my enzyme-adapter-react-16 to v1.12.1, that sorted it out for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.