简体   繁体   中英

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. I tried to extract out only the relevant parts below:

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);
  })
});

The test 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? 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. The final code is something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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