【发布时间】:2021-03-26 16:44:49
【问题描述】:
我在这里测试我的自定义钩子。
如果调用了signIn方法,无论如何都会调用history.push。
// Test.js
import myHandler from "./useMyHandler";
import { renderHook, act } from "@testing-library/react-hooks";
const mockhistoryPush = jest.fn();
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useHistory: () => ({
push: mockhistoryPush,
}),
}));
describe("auth handler hook", () => {
it("calls signin method and check user type", async () => {
const { result } = renderHook(() => useAuthHandler());
const { signIn } = result.current;
signIn("username", "1234");
expect(Auth.signIn).toBeCalledTimes(1);
expect(mockhistoryPush).toBeCalled();
});
});
逻辑是
const redirectToMain = () => {
history.push("/main");
};
const signIn = async (username, pwd) => {
let user = await Auth.signIn(username, pwd);
// work with user
redirectToMain();
};
我期待expect(mockhistoryPush).toBeCalled(); 是真的,但实际上它并没有说
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
它肯定达到redirectToMain 函数,甚至console.log(history) 显示历史是模拟函数。
我在这里做错了什么?
【问题讨论】:
标签: reactjs unit-testing jestjs react-hooks