4

我有一个这样的模块“sitecollection”:

var site = require('./site');    // <- this should be stubbed

var sitesCollection = function(spec) {

  var that = {};

  that.sites = {};

  that.findOrCreateById = function(id) {
    if (typeof(that.sites[id]) == "undefined") {
      that.sites[id] = site({id: id});            // <- its used here
    }
    return that.sites[id];
  };

  return that;
};

module.exports = sitesCollection;

所以在sitescollection 中,site 是一个不被导出的模块。但在代码内部,我使用它。现在我正在为#findOrCreateById() 编写茉莉花规格。

我想指定我的 findOrCreateBy() 函数。但我想存根 site() 函数,因为规范应该独立于实现。我必须在哪里创建 spyed 方法?

var sitescollection = require('../../lib/sitescollection');

describe("#findOrCreateById", function() {
  it("should return the site", function() {
    var sites = sitescollection();
    mysite = { id: "bla" };
    // Here i want to stub the site() method inside the sitescollection module.
    // spyOn(???,"site").andRetur(mysite);
    expect(sites.findOrCreateById(mysite.id)).toEqual(mysite);
  });
});
4

1 回答 1

1

您可以使用 https://github.com/thlorenz/proxyquire 实现此目的

var proxyquire = require('proxyquire');

describe("#findOrCreateById", function() {
    it("should return the site", function() {

        // the path '../../lib/sitescollection' is relative to this test file
        var sitesCollection = proxyquire('../../lib/sitescollection', {
            // the path './site' is relative to sitescollection, it basically
            // should be an exact match for the path passed to require in the
            // file you want to test
            './site': function() {
                console.log('fake version of "./site" is called');
            }
        });

        // now call your sitesCollection, which is using your fake './site'
        var sites = sitesCollection();
        var mysite = {
            id: "bla"
        };

        expect(sites.findOrCreateById(mysite.id)).toEqual(mysite);
    });
});
于 2017-01-23T15:27:51.270 回答