javascript - 如何测试按钮是否被点击?

标签 javascript reactjs jestjs react-testing-library

我正在使用 React 测试库。我遇到的问题是 fireEvent 没有触发,并且抛出错误,如下:

   Expected number of calls: >= 1
   Received number of calls:   0

对于这个特定的测试,我需要使用@testing-library/react-hooks吗?我是否需要将我的 Product 组件渲染在导入函数的上下文提供程序上?

Product.tsx 组件

import React, { FunctionComponent } from "react";
import { useProducts } from "./ContextWrapper";
import { Button } from "@mui/material";
import { articleProps } from "./types";

const Product: FunctionComponent<{ article: articleProps }> = ({
  article,
}) => {
  const { handleAddToCart } = useProducts(); // this is from global context
  return (
      <Button
        aria-label="AddToCart"
        onClick={() => handleAddToCart(article)}
      >
        Add to cart
      </Button>

  );
};

export default Product;

Product.test.tsx

import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import Product from "./Product";
import { act, renderHook } from "@testing-library/react-hooks";

const article = {
  name: "samsung",
  variantName: "phone",
  categories: [],
};

const renderProduct = () => {
  return render(
    <ContextProvider>
      <Product article={article} />
    </ContextProvider>
  );
};

//first test just tests if button exists with provided content and works fine
test("renders product", () => {
  render(<Product article={article} />);
  const AddToCartbutton = screen.getByRole("button", { name: /AddToCart/i });
  expect(AddToCartbutton).toHaveTextContent("Add to cart");
});
// this test throws the error described above
test("test addToCart button", () => {
  renderProduct();
  const onAddToCart = jest.fn();
  const AddToCartbutton = screen.getByRole("button", { name: /AddToCart/i });
  fireEvent.click(AddToCartbutton);
  expect(onAddToCart).toHaveBeenCalled();
});

ContextWrapper.tsx

import React, {createContext, useContext, ReactNode, useState} from "react";
import { prodProps } from "../types";

type ProductContextProps = {
  productData: prodProps;
  handleAddToCart: (clickedItem: productPropsWithAmount) => void;

};

const ProductContextDefaultValues: ProductContextProps = {
  productData: null as any,
  handleAddToCart:null as any;
};

type Props = {
  children: ReactNode;
};

const ProductContext = createContext<ProductContextProps>(
  ProductContextDefaultValues
);

export function useProducts() {
  return useContext(ProductContext);
}

const ContextWrapper = ({ children }: Props) => {
  const { data } = useGraphQlData();
  const [productData, setProductData] = useState<Category>(data);
  const [cartItems, setCartItems] = useState<prodProps[]>([]);

  useEffect(() => {
    if (data) {
      setProductData(data);
    }
  }, [data]);

  const handleAddToCart = (clickedItem: prodProps) => {
    setCartItems((prev: prodProps[]) => {
      return [...prev, { ...clickedItem }];
    });
  };

  return (
    <ProductContext.Provider
      value={{
        productData,
        handleAddToCart,
      }}
    >
      {children}
    </ProductContext.Provider>
  );
};

export default ContextWrapper;

最佳答案

我建议您创建按钮组件并单独测试它,如下所示:

const onClickButton = jest.fn();
await render(<Button onClick={onClickButton} />);
const AddToCartbutton = screen.getByRole("button", { name: /AddToCart/i });
await fireEvent.click(AddToCartbutton);
expect(onClickButton).toHaveBeenCalled();

关于javascript - 如何测试按钮是否被点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72276043/

相关文章:

reactjs - 组件如何对其子组件进行布局?

javascript - 特拉维斯/杰斯特 : TypeError: Cannot assign to read only property 'Symbol(Symbol.toStringTag)' of object '#<process>'

javascript - 尝试测试 create-react-app 项目时出现 "ReferenceError: document is not defined"

javascript - enzyme :如何测试浅层组件的交互

javascript - 获取数据时如何迭代不同的URL?

javascript - 滚动问题时左右移动元素

javascript - 什么时候应该在 Redux reducer 中深度克隆状态的哪一部分?

reactjs - 单元测试 navigator.permissions.query({ name : 'geolocation' }) using Jest (React)

javascript - 当我的导航栏折叠时如何使按钮起作用?

javascript - Jquery 自动调用事件或函数