问题:我正在尝试使用带有我的React组件的Jest来实现100%的测试覆盖率,但是似乎无法检测到正在调用的函数。我尝试仅提取以下相关部分:
LinkedRepos.js:
import { auth } from "../../firebase";
import React, { useEffect } from "react";
import { navigate } from "@reach/router";
const ReposPage = () => {
React.useEffect(() => {
auth.onAuthStateChanged(function (user) {
if (!user) {
console.log("DEBUGGING NO USER");
navigate("/");
}
});
}, []);
};
export default ReposPage;
LinkedRepos.test.js
import React from "react";
import { shallow } from "enzyme";
import ReposPage from "../Components/Pages/LinkedRepos";
import { navigate } from "@reach/router";
jest.mock('@reach/router', () => ({
navigate: jest.fn(),
}))
describe("Linked repos page", () => {
it("not logged in", () => {
jest.clearAllMocks();
jest.spyOn(React, 'useEffect').mockImplementation(f => f());
const repopage = shallow(<ReposPage />);
expect(navigate).toHaveBeenCalledTimes(1);
})
});
测试输出:
● Linked repos page › not logged in
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
....
console.log src/Components/Pages/LinkedRepos.js:14
DEBUGGING NO USER
我似乎找不到适用于我的问题的答案。我知道我的代码很糟糕,但是没有人知道为什么它无法检测到被调用的“导航”功能的原因吗?显然,它已达到代码中的这一点,因为它正在打印出我的调试消息。我似乎无法全神贯注于测试。
答案 0 :(得分:0)
事实证明,我只是需要一个等待语句才能让Jest识别出正在调用Navigation。最终的代码是这样的:
it("should call navigate once if not logged in", async () => {
await mount(<ReposPage />);
expect(navigate).toHaveBeenCalledTimes(1);
});