简体   繁体   中英

how to test javascript chain of promises?

I have a javascript promise similar to this:

function a(){
return new Promise(function(resolve, reject){
    b().then(function(result){
        if(result.name == 'sampletest1'){
            resolve({
                'data': 'testdata1'
            });
        }else if(result.name=='sampletest2'){
            resolve({
                'data': 'testdata2'
            });
        }
    }, reject);
})
}

I want to write test in jasmine to test functionality of function a . But I am having trouble as this function is dependent on the result of function b , which is also a promise. So, how to mock function b , so that I would be able to test functionality of function a .

Do not return an extra promise:

function a() {

  return b().then(function(result) {
    if (result.name == 'sampletest1') {
      return {
        'data': 'testdata1'
      };
    } else if (result.name == 'sampletest2') {
      return {
        'data': 'testdata2'
      };
    }
  });

}

Mocking b would be as simple as:

b = function () {
    return new Promise(function (resolve) {
        resolve({ name: 'sampletest1' });
    });
};

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