gpt4 book ai didi

node.js - 如何监视未导出的属性

转载 作者:搜寻专家 更新时间:2023-10-31 23:27:52 25 4
gpt4 key购买 nike

我有一个像这样的模块“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() 编写 jasmine 规范。

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

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

最佳答案

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

关于node.js - 如何监视未导出的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11867009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com