0

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?

6
  • 1
    SuperTest doesn't have any props as you are passing onClick Commented Nov 2, 2020 at 8:20
  • login should invoke props.onClick. Commented Nov 2, 2020 at 8:26
  • Can you provide a working code sample please? @DrewReese Commented Nov 2, 2020 at 8:43
  • 1
    No, just change SuperTest to consume an onClick prop and call it in the login function that is already attached to the onClick handler of the button element. Commented Nov 2, 2020 at 8:45
  • 2
    const btn = wrapper.find("#loginBtn"); Commented Nov 2, 2020 at 9:04

1 Answer 1

1

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);
      });
    });
Sign up to request clarification or add additional context in comments.

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.