2016-08-17 82 views
0

我有,我已經寫測試用例興農間諜回調不被稱爲

var debug = require('debug')('kc-feed:source:fb'); 
var request = require('request'); 
var config = require('../../config').root; 


exports.source = function fetchFeed (callback) { 
    var params = { 
     headers: {'content-type' : 'application/jsons'}, 
     url: config.host + "v1/social/fb/sync_feed", 
     method: 'GET' 
    }; 

    request(params, function(err, body, response) { 
    if(err) { 
     callback(err); 
    } 
    else { 
     var raw_data = JSON.parse(response); 
     callback(null, raw_data); 
    } 
    }); 
}; 

我的源文件,這是我的摩卡測試用例

var chai = require('chai'), 
    expect = chai.expect, 
    app = require('../app'), 
    rewire = require('rewire'), 
    fbfeed = rewire('../src/feed/source/fb_feed'), 
    supertest = require('supertest'), 
    sinon = require('sinon'), 
    nock = require('nock'); 

describe('test cases for fb feed file', function() { 
    var callback; 
    beforeEach(function(){ 
     callback = sinon.spy();  
    }); 

    after(function(){ 
     nock.cleanAll(); 
    }); 

    it('callback should be called with the response', function(done) { 
     nock('http://localhost:3000/') 
      .get('/v1/social/fb/sync_feed') 
      .reply(200, {}); 
      callback = sinon.spy(); 
     fbfeed.source(callback); 
     sinon.assert.calledOnce(callback); 
     done(); 
    }); 

    it('callback should be called with the error', function(done) { 
     nock('http://localhost:3000/') 
      .get('/v1/social/fb/sync_feed') 
      .replyWithError(new Error('err')); 
     fbfeed.source(callback); 
     sinon.assert.calledOnce(callback); 
     done(); 
    }); 

我的兩個測試案例失敗,因爲它說回調被稱爲0次。但回調總是被調用。請幫忙。

回答

0

看起來這些請求仍然是異步執行的(我不能確定地說,如果這是預期使用nock),所以你不能使用這樣的間諜。

提供而不是常規的回調:)

fbfeed.source(function(err, raw_data) { 
    ...make your assertions... 
    done(); 
}); 
+0

它(,函數(完成){ \t \t諾克( '://本地主機3000/HTTP' '回調應該與錯誤稱爲' \t \t \t獲得( '/ V1 /社會/ FB/sync_feed')\t \t \t \t .replyWithError(新錯誤( 'ERR')); \t \t fbfeed.source(功能(ERR,RAWDATA){ \t \t \t expect(err).to.equal('err'); \t \t \t done() \t \t}); \t}); 我得到錯誤Uncaught AssertionError:expected [Error:err] to equal'err' – krish

+0

'err'是一個對象,而不是一個字符串。嘗試'expect(err.message).to.equal('err')'。 – robertklep

+0

謝謝!有用。我不明白錯誤的類型。現在它工作@robertklep – krish