断言传递给模拟函数的回调已被调用

时间:2020-10-06 08:29:21

标签: javascript jestjs mocking

以下setState挂钩传递给ageVerificationService,然后调用 点击事件。我的问题是此服务已在我的单元测试中被嘲笑,所以我无法 断言setState挂钩已被调用。

如何模拟我的服务,以便它调用任何传递的函数?

  // SetState Hook
  ageVerified && setIsVerified(true);

  // AgeVeri Service
  ageVerificationService(dispatch, () => setIsVerified(!isVerified));

单元测试

// Mocking setState hook
const setState = jest.fn();
const useStateMock: any = (initState: any) => [false, setState];
    (useState as jest.Mock).mockImplementation(useStateMock);

// Mocking the service
jest.mock('../../../services/ageverification', () => jest.fn());

expect(ageVerificationService).toBeCalledWith(
  mockDispatch,
  expect.any(Function)
);

expect(setState).toHaveBeCalled(); // Failing as not called by mocked service

1 个答案:

答案 0 :(得分:0)

(ageVerificationService as jest.Mock).mockImplementation(
      (dispatch: Dispatch, callback: Function) => {
        callback();
      }
    );

我只是向AgeVerification服务添加了一个模拟实现