我想用jest为react tsx文件中的函数编写测试用例

dly7yett  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(188)

在我的Header.tsx中
功能:

const mobileMenuToggle: toggleMobileMenu = () => setIsNavOpen((prev) => !prev);

按钮的位置:

<button
        data-testid="hamburgerBtn"
        className="HAMBURGER-ICON space-y-2 px-5 "
        onClick={mobileMenuToggle}
      >
        <span className=""></span>
        <span className=""></span>
        <span className=""></span>
      </button>

Header.test.tsx

test("hamburgerMenuToggle button called", () => {
const mockFunction = jest.fn();
render(
  <button onClick={mockFunction}>
    <span className=""></span>
    <span className=""></span>
    <span className=""></span>
  </button>
);
// expect(screen.getByRole("button")).toBeInTheDocument();
expect(mockFunction).toHaveBeenCalled();
});

我试图为它编写测试用例,但不知道如何从我的Header.tsx文件中定位它

ldioqlga

ldioqlga1#

应该使用fireEvent并添加data-testid="hamburgerBtn"

export interface IHamburgerMenuToggleProps {
  onClick?: () => void;
}
const HamburgerMenuToggle = ({ onClick }: IHamburgerMenuToggleProps) => {
  return (
    <button
      data-testid="hamburgerBtn"
      className="HAMBURGER-ICON space-y-2 px-5 "
      onClick={onClick}
    >
      <span className="" />
      <span className="" />
      <span className="" />
    </button>
  );
};
export default HamburgerMenuToggle;

//tests
import {
      fireEvent,
      render
    } from "@testing-library/react";
import HamburgerMenuToggle from "./hamburgerMenuToggle";

test("hamburgerMenuToggle button called", () => {
  const mockFunction = jest.fn();
  const { getByTestId } = render(
    <button data-testid="hamburgerBtn" onClick={mockFunction}>
      <span className=""></span>
      <span className=""></span>
      <span className=""></span>
    </button>
  );
  const button = getByTestId("hamburgerBtn");
  fireEvent.click(button);
  expect(mockFunction).toHaveBeenCalled();
});

test("hamburgerMenuToggle button called using component", () => {
  const mockFunction = jest.fn();
  const { getByTestId } = render(
    <HamburgerMenuToggle onClick={mockFunction} />
  );
  const button = getByTestId("hamburgerBtn");
  fireEvent.click(button);
  expect(mockFunction).toHaveBeenCalled();
});

相关问题