Aamir
Aamir

Reputation: 15566

Mock a button click in React with Jest and Enzyme

I am trying to run a simple unit test which is trying to mock a button click event. For some reason, my mock method is not getting called. Here is the React JS file:

import React from "react";

function SuperTest(props) {
  const login = (e) => {
    props.onClick();
    console.log("Somebody clicked me!!!");
  };

  return (
    <div id="header" className="header-container">
      <button type="button" id="loginBtn" text="Login" onClick={login} />
    </div>
  );
}

export default SuperTest;

And here is the Unit test:

import React from "react";
import { render } from "@testing-library/react";
import { shallow, mount } from "enzyme";
import SuperTest from "../components/SuperTest";

describe("Click tests", () => {
  it("testing login click", () => {
    const clickMock = jest.fn();
    const wrapper = mount(<SuperTest onClick={clickMock} />);
    const btn = wrapper.find("#header");
    if (btn) btn.simulate("click");
    expect(clickMock.mock.calls.length).toBe(1);
  });
});

This is the result of the unit test run that I am getting:

src/tests/LoginAccountSelector.test.js
  ● Click tests › testing login click

    expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

      32 |     const btn = wrapper.find("#header");
      33 |     if (btn) btn.simulate("click");
    > 34 |     expect(clickMock.mock.calls.length).toBe(1);
         |                                         ^
      35 |   });
      36 | });
      37 | 

      at Object.it (src/tests/LoginAccountSelector.test.js:34:41)

Can anybody point me to what I am doign wrong here?

Upvotes: 0

Views: 4249

Answers (1)

Sarun UK
Sarun UK

Reputation: 6736

Try this approach,

describe("Click tests", () => {
      it("testing login click", () => {
        const clickMock = jest.fn();
        const wrapper = mount(<SuperTest onClick={clickMock} />);
        const btn = wrapper.find("#loginBtn");
        if (btn) btn.simulate("click");
        expect(clickMock.mock.calls.length).toBe(1);
      });
    });

Upvotes: 1

Related Questions