如何编写测试用例以覆盖Promise链中所有嵌套的“ then”回调

时间:2019-04-29 18:01:39

标签: reactjs unit-testing ecmascript-6 jestjs

我很难在单元测试中涵盖整个承诺链。我确实找到了可以为我提供最接近解决方案的文章,但是挑战在于最后一个“ then”,我需要调用三个不返回承诺的函数。

下面是我尝试过的示例/示例

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

下面是返回带有嵌套“ then”函数的另一个函数的函数。我需要测试用例的帮助才能涵盖所有内容。

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

我很难覆盖嵌套的then函数。

1 个答案:

答案 0 :(得分:0)

您将嘲笑functionOne等每个解析值:

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

这不完全是您的代码,但是想法就这样。您可以模拟每个函数的解析值。