我有一个 Input 组件,它接受一个 prop 方法并在用户输入内容时调用它。代码本身按预期工作,但由于某些原因,测试失败。它认为没有调用 prop 方法。为什么会这样?出于测试目的,我使用 Jest 和 react-testing-library。
第二个问题。在实际应用中,我的想法是测试传递给该 prop 方法的参数。它是否被认为是一个实现测试(我知道我应该测试它)?
输入.js
export default function Input({ onChange }) {
  return <input onChange={onChange} />;
}
测试
import React from "react";
import { render, act, cleanup, fireEvent } from "react-testing-library";
import Input from "./input";
describe("Input tests", () => {
  afterEach(cleanup);
  it("Should call prop function", () => {
    const onChange = jest.fn();
    const { getByTestId } = render(<Input onChange={onChange} />);
    const input = getByTestId("input");
    act(() => {
      fireEvent.change(input, { target: { value: "Q" } });
    });
    expect(onChange).toHaveBeenCalled();
  });
});