mardi 1 décembre 2020

How to test onClick event of a button?

I have a component in which I have a Button and onClick of Button I am calling a function handleClick. and I wanted to test my Button

MyFoo.js

import React, { useState, useEffect } from "react";
import {Button} from "some/depend"
//imports

export default function MyFoo() {
  const [value, setValue] = useState({});
  const [show, setShow] = useState(false);

  const handleClick= () => {
    //value = {email: "A", name: "B"}
    if (Object.keys(value).length !== 0) {
      localStorage.setItem("values", JSON.stringify(value));
      setShow(true);
    }
  };

  return (
    <>
       <div className="myClass">
        <Button
        text="MYButton"
        className="my-btn"
        onClick={handleClick}
        id="myBtn"
      />
      </div>
    </>
  );
}

I have tried to create an instance for testing but getting error handleClick of null

MyFoo.test.js

  describe("Executes a handler function", () => {
    it("must call the mock method with button click", () => {
      const wrapper = shallow(<MyFoo />);
      const button = wrapper.find(#myBtn);
      const instance = wrapper.instance();

      instance.handleClick = jest.fn(instance.handleClick);

      button.simulate("click");
      expect(instance.handleClick).toHaveBeenCalled();
    });
  });

Looking for a solution how to test onClick event for a button.

Aucun commentaire:

Enregistrer un commentaire