如何在开玩笑的承诺之后测试 then 部分

nkp*_*tel 2 testing reactjs jestjs

我正在处理一个 React 项目,并且正在使用 jest 为我的代码编写测试。

这是我要测试的代码。

const handleSubmit = (handleSuccess, handleErrors) => {
  signupAPI(user)
    .then(handleSuccess)
    .catch(handleErrors);
};
Run Code Online (Sandbox Code Playgroud)

这是测试代码:

test('should call handleSuccess', () => {
  signupAPI.mockImplementation((user) => Promise.resolve(user));
  const handleSuccess = jest.fn();
  const handleErrors = jest.fn();

  handleSubmit(handleSuccess, handleErrors); 

  expect(signupAPI).toHaveBeenCalled(); // test passes

  expect(handleSuccess).toHaveBeenCalled(); // test fails
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,它永远不会在承诺之后移动到“then”部分。如何测试 then 部分中的函数是否被实际调用?

And*_*rle 6

问题是你没有等待你在测试中创建的承诺:

test('should call handleSuccess', async() => {
  const p = Promise.resolve()
  signupAPI.mockImplementation((user) => p.then(user));
  const handleSuccess = jest.fn();
  const handleErrors = jest.fn();

  handleSubmit(handleSuccess, handleErrors); 
  await p
  expect(signupAPI).toHaveBeenCalled(); // test passes

  expect(handleSuccess).toHaveBeenCalled(); // test fails
});
Run Code Online (Sandbox Code Playgroud)