Jasmine 如何使预先解决的承诺同步继续测试

Jasmine 如何使预先解决的承诺同步继续测试,jasmine,jestjs,babel-jest,Jasmine,Jestjs,Babel Jest,如果我有一些代码导致某些事情异步发生,但不是做某事的根本原因(不能等待回调),那么在循环中发生的事情(即测试autosave)将是最好的方法 下面是一个失败的测试示例,大致说明了我试图实现的目标 function myProgram(something, onEvent) { something().then(() => onEvent()); } test('Promise test', () => { const onEvent = jest.fn(); exp

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

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

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.
})

你必须从你的测试中返回承诺

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.
})
还可以看看