简体   繁体   中英

How to write test cases to cover all the nested 'then' callbacks in a promise chain

I'm having difficulty covering the entire promise chain in my unit test coverage. I did find articles that gave me the nearest solution but the challenge is at the last 'then' I need to call three function that does not return a promise.

Below is the example/Sample I tried

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

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

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


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

Below is the function which returns another function with nested 'then' functions. I need help with the test cases to cover them all.

function consolidatedReport(param1, param2){

   const somedata = param1.data;
   const someOtherData = param2.data;

  if(true){ 
     doThisthing(); 
   }

  return promiseChainBegin(somedata, someOtherData)
    .then(response => response && functionOne(somedata, someOtherData)
    .then(response => response && functionTwo(somedata, someOtherData)
    .then(response => response && functionThree(somedata, someOtherData)
    .then(response => response && functionFour(somedata, someOtherData)
    .then(response => {
       if(response) {
           notApromiseFuncOne(somedata)(someOtherData);
           notApromiseFuncTwo(somedata)(someOtherData);
           notApromiseFuncThree(somedata)(someOtherData);
        } else{
           notApromiseFailCase(someOtherData);
        }
    });
}

I'm having difficulty covering the nested then functions.

You'd mock each of functionOne , etc resolved values:

import functionOne from '../path/to/functionOne';
import functionTwo from '../path/to/functionTwo';
import functionThree from '../path/to/functionThree';

jest.mock('../path/to/functionOne');
jest.mock('../path/to/functionTwo');
jest.mock('../path/to/functionThree');

it('test my scenario', () => {
  functionOne.mockResolvedValue('value 1');
  functionTwo.mockResolvedValue('value 2');
  functionTwo.mockResolvedValue('value 3');

  return someChainPromisesMethod()
    .then(data => {
      expect(functionOne).toBeCalledWith('value returned by promise');
      expect(functionTwo).toBeCalledWith('value 1');
      expect(functionThree).toBeCalledWith('value 2');

      expect(data).toEqual('Final Value');
  });
});

This is not exactly your code, but the idea goes like that. You mock the resolved value for each of your functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM