React:回调不被计入Jest测试中的调用

luaexgnf  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(173)

我已经简化了我的代码用于示例目的,但仍然不明白为什么Jest测试失败。
该组件是一个按钮,当单击该按钮时,它会执行API获取,然后执行prop回调调用。
在测试中,我获取按钮并单击它。测试计数获取调用。但是当我检查回调时,测试失败。
不知道为什么。

// @ts-nocheck
import { render, screen, fireEvent } from "@testing-library/react";
import jest from 'jest-mock';

const ClickTarget = ({ onSuccess }) => {
  async function handleClick() {
    try {
      const response = await fetch('/api/posts/');
      console.log(response);
    } catch (error) {
      console.error(error);
    }

    onSuccess('Done');
  }

  return (
    <button onClick={() => handleClick()} data-testid="saveBtn" type="button">
      Save
    </button>
  );
};

// JEST TEST
global.fetch = jest.fn(() =>
  Promise.resolve({ "content": "test" })
);

console.log = () => { };

describe("ClickTarget component", () => {

  it("should call API then callback", () => {
    const mockSuccessCb = jest.fn();

    render(<ClickTarget onSuccess={mockSuccessCb} />);

    const btn = screen.getByTestId('saveBtn');
    expect(btn).toBeInTheDocument();
    fireEvent.click(btn)
    expect(fetch).toHaveBeenCalledTimes(1);
    expect(fetch.mock.calls[0][0]).toContain("/api/posts/");

    // test fails HERE onSuccess called after fetch not recognized
    expect(mockSuccessCb).toHaveBeenCalledTimes(1);
    expect(mockSuccessCb.mock.calls[0][0]).toBe('Done');

  });
});

字符串

ymzxtsji

ymzxtsji1#

我发现我需要让检查等待,因为fetch调用是一个fetch调用,它抛出了计时。将测试更改为fetch,然后使用带有超时的waitFor

it("should Save content on submit", async () => {

...

await waitFor(()=> expect(mockSuccessCb).toHaveBeenCalledTimes(1), {timeout: 1000});

字符串

相关问题