运行诺言后未调用玩笑功能

时间:2019-02-26 07:23:03

标签: jestjs

我使用Jest和酶解决了诺言之后,尝试测试这些方法。我的组件/功能代码:

// Functional Code
let functionAfterAsync = () => {
  console.log('functionAfterAsync called');
}
const asyncFunction = () => {
  return new Promise(resolve => resolve());
}
const functionWithAsyncCode = () => {
  // ... some more code here
  console.log('functionWithAsyncCode');
  asyncFunction().then((res: any) => {
    functionAfterAsync();
  })
}

我的测试:

functionAfterAsync = jest.fn();
// Tests
describe('<Async Test />', () => {
    it('Call function after promise', () => {
      functionWithAsyncCode();
      expect(functionAfterAsync).toBeCalled();
    })
});

但是functionAfterAsync没有被调用,我得到的错误是: expect(jest.fn()).toBeCalled() Expected mock function to have been called.

有没有办法做到这一点。谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在断言functionAfterAsync被调用之前,您需要wait for the Promise to resolve

最简单的方法是从Promise返回functionWithAsyncCode

const functionWithAsyncCode = () => {
  console.log('functionWithAsyncCode');
  return asyncFunction().then(() => {  // return the Promise
    functionAfterAsync();
  })
}

...然后在测试中wait for it to resolve

it('Call function after promise', async () => {  // use an async test function
  await functionWithAsyncCode();  // wait for the Promise to resolve
  expect(functionAfterAsync).toBeCalled();  // SUCCESS
})

或者,您可以在.thenreturn the Promise from your test function中声明:

it('Call function after promise', () => {
  return functionWithAsyncCode().then(() => {  // return the Promise
    expect(functionAfterAsync).toBeCalled();  // SUCCESS
  });
})