尽管通过传递jest.fn作为道具,但未调用模拟函数

时间:2020-09-22 03:30:14

标签: reactjs react-testing-library

我正在尝试使用

来测试此组件的选择功能

https://www.npmjs.com/package/react-giphy-searchbox

我正在这样使用它

GifSection.tsx

import React, { Fragment } from "react";
import ReactGiphySearchbox from "react-giphy-searchbox";
import "./style.css";
type GifType = {
  apiKey: string;
  select: (e: any) => void;
};
const GifSection: React.FC<GifType> = (props) => {
  const { apiKey, select } = props;
  return (
    <div data-testid="gif-section">
      <ReactGiphySearchbox
        data-testid="search-box"
        wrapperClassName="gifForm"
        searchFormClassName={{ padding: "20px 0px" }}
        apiKey={apiKey}
        onSelect={(e) => select(e)}
        masonryConfig={[
          { columns: 4, imageWidth: 110, gutter: 5 },
          { mq: "1000px", columns: 4, imageWidth: 120, gutter: 5 },
        ]}
      />
    </div>
  );
};
export default GifSection;

GifSection.test.tsx

it("should test onSelect", () => {
    const mockSelect = jest.fn();
    render(
      <GifSection
        apiKey="****************"
        select={mockSelect}
      />
    );
    expect(mockSelect).toBeCalledTimes(1);
});

我正在得到

expect(jest.fn())。toBeCalledTimes(expected)

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

我不确定为什么会这样,这可能是第三方插件本身吗?

为了更好地了解第三者本身,

  // screen.debug(screen.getByTestId("SearchFormInput"));
  // console.log
  // <input
  //   class="input"
  //   data-testid="SearchFormInput"
  //   name="search"
  //   placeholder="Search for GIFs"
  //   type="text"
  //   value=""
  // />

1 个答案:

答案 0 :(得分:1)

在触发变更事件之前,不会触发

onSelect={(e) => select(e)}。您应该从测试文件中触发一个screen.click事件。

特定于API

正在寻找react-giphy-searchboxonSelect的文档: REQUIRED只要选择了GIF,就会触发一个回调。它以Giphy API中为图片指定的格式返回Gif对象。因此,只需单击即可(如我建议的那样无效)。

您应该使用screen.debug来查看正在生成的html,并尝试以这种方式进行选择,但老实说,您不应在测试时调用API。您基本上是在测试不是您的工作的GIPHY服务,还是正在测试React中的prop系统,而这也不是您的工作。