简体   繁体   中英

Unit testing javascript promises

My code fetches data from a server via ajax and uses promises.

How do I write a unit text for this code?

function getPromise(){ 
  var p = new Promise(function(resolve, reject) { 
    http.get({ 
      host: 'localhost', 
      port: 3000, 
      path: '/blist'
    }, function(res) { 
      if(res.statusCode < 200 || res.statusCode>300) { 
        reject('statusCode=' + res.statusCode); 
        return; 
      } 
      var data=""; 
      res.on('data', function (chunk) { 
        data += chunk; 
        resolve(data); 
        return; 
      }); 
      res.on('error', function(error) { 
        console.log("Got error: " + e.message); 
        reject(error); 
      }); 
    }) 
  }); 
  return p; 
}

You can mock the server response with nock and assert the promise value via mocha

describe('promise' function (done) {
  getPromise.then(response => {
    // assert response
    done()
  })
}

I guess you'd want to test the promise function, whether it's gonna do what's expected if you fake an http call.

For that you might wanna consider passing in http object and the callback it takes as parameters so you can mock them and simulate the success and error responses in your tests.

Something like

getPromise(http, req, callback) {
  var promise = new Promise((resolve, reject) -> {
    http.get(req, callback);
    callback.on('data', data -> { // Resolve or reject looking at the status code })
  })
  return promise;
}

Then you can mock your callback as well as http#get function to test your scenarios

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