如何监视未导出的属性

时间:2012-08-08 14:42:34

标签: node.js jasmine stubbing spy

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用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);
    });
});