0

If I have a bit of code that cause something to happen async but not as a root cause of doing something (can't wait for the callback), something that happens on loop (i.e. testing autosave) how would be the best way todo it.

Here is a failing tests example of roughly what im trying to achieve.

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.
})
Saspiron
  • 180
  • 1
  • 10

1 Answers1

0

You have either to return the promise from your test

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

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

Also have a look at the docs

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297