2016-10-12 54 views
0

我正在使用testdouble.js來測試幾個函數。對於下面的函數,我正在努力弄清楚如何最好地存儲get API調用,以覆蓋剩餘的函數。看起來應該是直截了當的,但我認爲我一直盯着它太久了。使用Testdouble.js存根API調用並解決承諾

var checkTags = function(tags) { 
    return new Promise(function(resolve) { 

     /* istanbul ignore if */ 
     if (process.env.NODE_ENV !== 'test') { 
      console.log("Entered Check Tags"); 
     } 
     var tagMSG; 
     var url = 'https://api.to.call/'; 
     tags.Tags.forEach(function(uaiTag) { 
      tagMSG = uaiTag.Key === 'UAI' ? uaiTag.Value : 'No Tag'; 
     }); 
     console.log(tagMSG); 
     if (tagMSG === "No Tag") return resolve('FAILED'); 
     request.get(url + tagMSG, function(error, response) { 
      var returnStatus = 'FAILED'; 
      console.log(returnStatus); 
      if (!error && response.statusCode === 200) { 
       returnStatus = 'PASSED'; 
      } 
      return resolve(returnStatus); 
     }) 
    }); 
}; 

我的測試看起來像下面:

it('should resolve2', function(done) { 
    td.replace(request, 'get', function() { 
     return new Promise((resolve) => resolve('PASSED')); 
    }); 

    var policy = require('../main/js-utils'); 
    should(policy.checkTags(require('./data/tags.json'))).be.equal(new Promise((resolve) => resolve())); 
    }); 

而我收到的錯誤:

AssertionError: expected [Promise] to be [Promise] 
    + expected - actual 

    { 
    - "_bitField": 0 
    + "_bitField": 33554432 
    "_fulfillmentHandler0": [undefined] 
    "_promise0": [undefined] 
    "_receiver0": [undefined] 
    - "_rejectionHandler0": [undefined] 
    + "_rejectionHandler0": "PASSED" 
    } 

回答

0

即使他們與解決這兩個不同的承諾永遠不會相等相同的結果(與{} === {}返回false相同)。 要解決此問題,您需要事先創建您的承諾,如下所示:

const promise = new Promise((resolve) => resolve('PASSED') 
td.replace(request, 'get', function() { 
    return promise 
}) 
var policy = require('../main/js-utils') 
should(policy.checkTags(require('./data/tags.json'))).be.equal(promise)