简体   繁体   English

useEffect 中的 Jest 测试函数调用

[英]Jest test function call inside useEffect

I have the following test:我有以下测试:

  it("should call runValidation when listen_to is set", async () => {
    const updatedProps = {
      item: {
        ...props.item,
        attributes: {
          ...props.item.attributes,
        },
      },
      validation: {
        ...props.validation,
        setValue: jest.fn(),
        runValidation: jest.fn(),
        listenFieldValues: jest.fn(),
      },
    };

    const spyOnValidation = jest.spyOn(
      updatedProps.validation,
      "runValidation"
    );

    render(<Average item={updatedProps.item} validation={props.validation} />);

    expect(spyOnValidation).toHaveBeenCalled();
  });

and this is the UI related to it:这是与之相关的用户界面:

export const Average = ({ item, validation }: ComponentProps): JSX.Element => {
  const { attributes, name } = item;

  const hide_cents = attributes?.hide_cents;
  const [price, setPrice] = useState<number>(Number(item.value || 0));

  useEffect(() => {
    if (attributes?.listen_to) {
      console.log("validation: ", validation);
      setupListenData({ item, validation, callback: setPrice });
      validation.runValidation();
    }
  }, [item, attributes, validation]);
...

I am trying to test that validation.runValidation() is being called inside useEffect but the test is failing: number of calls 0我正在尝试测试在useEffect内部调用了validation.runValidation()但测试失败:调用次数 0

I have also tried to use waitFor but the test passes regardless of how many times haveBeenCalledTimes(3) or haveBeenCalledTimes(100)我也尝试过使用waitFor但无论有多少次haveBeenCalledTimes(3) or haveBeenCalledTimes(100)测试都通过了

Have you tried to create a mock function within this test, then assign the mock function to updatedProps.validation.runValidation , then you just expect the mock function is called?您是否尝试在此测试中创建一个模拟函数,然后将模拟函数分配给updatedProps.validation.runValidation ,然后您只期望调用模拟函数?

  it("should call runValidation when listen_to is set", () => {
    const mockRunValidation = jest.fn();
    const updatedProps = {
      item: {
        ...props.item,
        attributes: {
          ...props.item.attributes,
        },
      },
      validation: {
        ...props.validation,
        setValue: jest.fn(),
        runValidation: mockRunValidation,
        listenFieldValues: jest.fn(),
      },
    };
    render(<Average item={updatedProps.item} validation={props.validation} />);

    expect(mockRunValidation).toHaveBeenCalled();
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM