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

4

1 回答 1

0

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

改为提供常规回调:

fbfeed.source(function(err, raw_data) {
  ...make your assertions...
  done();
});
于 2016-08-17T08:17:03.847 回答