0

如果我有一些代码导致某些事情异步发生但不是做某事的根本原因(不能等待回调),那么在循环中发生的事情(即测试自动保存)如何是最好的方法呢? .

这是一个失败的测试示例,大致说明了我试图实现的目标。

function myProgram(something, onEvent) {
    something().then(() => onEvent());
}

test('Promise test', () => {
  const onEvent = jest.fn();
  expect(onEvent).not.toBeCalled();

  const doSomething = () => Promise.resolve();

  myProgram(doSomething, onEvent);

  expect(onEvent).toBeCalled();  // Expected mock function to have been called.
})
4

1 回答 1

0

你要么从你的测试中返回承诺

test('Promise test', () => {
  const onEvent = jest.fn();
  expect(onEvent).not.toBeCalled();

  const doSomething = () => Promise.resolve();

  myProgram(doSomething, onEvent);

  expect(onEvent).toBeCalled();  // Expected mock function to have been 
called.
  return doSomething
})

或使用async/await

test('Promise test', async() => {
  const onEvent = jest.fn();
  expect(onEvent).not.toBeCalled();

  const doSomething = await () => Promise.resolve();

  myProgram(doSomething, onEvent);

  expect(onEvent).toBeCalled();  // Expected mock function to have been called.
})

也看看文档

于 2017-02-08T13:34:25.643 回答