Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test promise-chain with Jest

I'm trying to test promises-chain sequence with Jest:

someChainPromisesMethod: function() {
    async()
      .then(async1)
      .then(async2)
      .then(result)
      .catch(error);
}

While testing single promise is good documented not sure what is a proper way (not sure what to do TBO) to test this kind of chain. Let's assume all asyncs are mocked and just resolves promises (Promise.resolve) in theirs body.

So I need something that will test whole sequence.

like image 667
Лёша Ан Avatar asked Apr 04 '16 10:04

Лёша Ан


1 Answers

You can use jest.fn() to mock implementation and check what the function has been called with and return what you want. You need to mock all async functions you have in your function and return what you want.

e.g.

async = jest.fn(() => {
  return Promise.resolve('value');
});

async1 = jest.fn(() => {
  return Promise.resolve('value1');
});

async2 = jest.fn(() => {
  return Promise.resolve('Final Value');
});

You can use this in your test as

it('should your test scenario', (done) => {
  someChainPromisesMethod()
    .then(data => {
      expect(async1).toBeCalledWith('value');
      expect(async2).toBeCalledWith('value1');
      expect(data).toEqual('Final Value');
      done(); 
  });
});

However, I would flatten your chain and test them separately if you have logic in them, that way you can test all possibilities easily.

like image 180
grgmo Avatar answered Sep 27 '22 19:09

grgmo