sinon 间谍作为回调未被调用

sinon spy as callback not being called

我有我的源文件,我已经为其编写了测试用例

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);
    }
  });
};

这是我的 mocha 测试用例

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 次。但是回调总是被调用。请帮忙

看起来请求仍在异步执行(我不能明确地说这在使用 nock 时是否是预期的),所以你不能那样使用间谍。

改为提供常规回调:

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