2015-08-24 65 views
2

我是單元測試的新手。我在Node.js中工作,我正在使用async module。這裏是我正在使用的代碼:使用Mocha/Chai來測試NodeJS的匿名回調代碼

module.exports = { 
    postYelp: function (cb, results) { 
     if (results.findLocation) { 
      results.client.post(['resources', 'Yelp'].join('/'), results.findLocation, function (err, data, ctx) { 
       /* istanbul ignore next */ 
       if (err) { 
        cb(err); 
       } else { 
        console.log('data', data); 
        console.log('ctx', ctx.statusCode); 
        return cb(null, ctx.statusCode); 
       } 
      }); 
     } 
     /* istanbul ignore next */ 
     else cb(null); 
    }, 
} 

因此,大家可以看到,在函數調用的第三個參數來results.client.post是一個匿名的回調。

我想測試這個回調的覆蓋範圍。如果我可以輕鬆地使用與回調相同的代碼重新創建一個命名的函數並替換它,我可以單獨測試它。但是,封閉函數(「postYelp」)有自己的回調函數(「cb」),它必須在匿名回調函數中使用。

我該如何測試這個匿名函數代碼?

回答

1

好的我想通了。我不必重構,只需找到一種方法將參數傳遞給匿名回調。下面的代碼:

describe('when postYelp method is called', function() { 
    it('should call the post method', function() { 
     var cbspy = sinon.spy(cb); 
     var post = sinon.stub(client, 'post'); 
     var results = {}; 
     results.client = {}; 
     results.client.post = post; 
     results.findLocation = {'id': 'lyfe-kitchen-palo-alto'}; 
     post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201}); 
     helpers.postYelp(cbspy, results); 
     assert(cbspy.called); 
     client.post.restore(); 
    }); 
}); 

基本上我使用興農創建內部函數(client.post)的殘餘部分。我在我的測試文件中需要客戶端和OUTER功能。此行讓我正確的參數輸送給內部函數:

post.callsArgWith(2, null, {'statusCode': 201}, {'statusCode': 201}); 

「2」指的是匿名的回調函數調用的方法後的第三個參數。 「null」是「err」參數,對象「{'statusCode':201}」實際上可以是任何值。

相關問題