简体   繁体   English

Jest/Enzyme Test Function Call in Callback

[英]Jest/Enzyme Test Function Call in Callback

Problem: I am trying to achieve 100% test coverage using Jest with my React component, but it just doesn't seem to detect the function being called.问题:我试图通过我的 React 组件使用 Jest 实现 100% 的测试覆盖率,但它似乎没有检测到正在调用的 function。 I tried to extract out only the relevant parts below:我试图仅提取以下相关部分:

LinkedRepos.js: 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 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);
  })
});

The test output:测试output:

  ● 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

I can't seem to find any answers that apply to my problem.我似乎找不到任何适用于我的问题的答案。 I know my code is quite bad, but does anyone know the reason why it won't detect the "navigate" function being called?我知道我的代码很糟糕,但有谁知道它无法检测到被调用的“导航”function 的原因吗? Clearly, it is reaching that point in the code, since it is printing out my debugging message.显然,它在代码中达到了这一点,因为它正在打印出我的调试消息。 I just can't seem to wrap my head around testing.我似乎无法全神贯注地进行测试。

It turns out I justed needed an await statement for Jest to recognise that navigate was being called.事实证明,我只是需要一个等待语句来让 Jest 识别出正在调用导航。 The final code is something like this:最终的代码是这样的:

it("should call navigate once if not logged in", async () => {
  await mount(<ReposPage />);
  expect(navigate).toHaveBeenCalledTimes(1);
});

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

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