提问人:RayJ_inSJ 提问时间:11/13/2023 更新时间:11/13/2023 访问量:25
React:回调在 Jest 测试中未被计为调用
React: Callback not being counted as called in Jest test
问:
我已经简化了我的代码以用于示例目的,但仍然不明白为什么 Jest 测试失败。
该组件是一个按钮,单击该按钮时,它会进行 API 获取,然后进行 prop 回调调用。
在测试中,我得到按钮并单击它。该测试对提取调用进行计数。但是当我检查回调时,测试失败了。
想不通为什么。TIA系列
// @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');
});
});
答:
0赞
RayJ_inSJ
11/13/2023
#1
我发现我需要让检查等待,因为获取调用是异步的,它会中断时间。 将测试更改为异步,然后使用带有超时的 waitFor
it("should Save content on submit", async () => {
...
await waitFor(()=> expect(mockSuccessCb).toHaveBeenCalledTimes(1), {timeout: 1000});
评论