【问题标题】:jest function mocked from module doesn't detect its call when it is called by other method从模块模拟的 jest 函数在被其他方法调用时没有检测到它的调用
【发布时间】: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


    【解决方案1】:

    我刚刚发现如果代码导致状态改变,应该用act API 包裹起来。

    由于我的 signIn 函数返回 Promise,它必须是这样的

    it("calls signin method and check user type", async () => {
        const { result } = renderHook(() => useAuthHandler());
        const { signIn } = result.current;
        await act(async () => {
          await signIn("username", "1234");
        });
        expect(Auth.signIn).toBeCalledTimes(1);
        expect(mockhistoryPush).toBeCalled();
      });
    

    现在它工作正常。希望对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      相关资源
      最近更新 更多