不需要节点ShouldJS



我的节点应用程序有一个相当大的测试套件,它依赖于ShouldJS模块。问题是,库阻止为对象分配.should属性,但我的测试套件需要启动一个需要可模拟的服务器(即在与我的测试套装相同的过程中运行),并动态构建ElasticSearch查询,该查询需要在对象上设置.should属性。

我尝试使用这里描述的方法来取消对ShouldJS的需求。但这并没有帮助——请参阅下面的示例脚本。是否有变通方法或替代方法?

示例:

require('should');
var objBefore = {};
objBefore.should    = 'should1';  // doesn't get assigned!
objBefore['should'] = 'should2';  // doesn't get assigned!
console.log('Before:', objBefore);
Object.keys(require.cache).forEach(function(path) {
  if (path.indexOf('/node_modules/should/') === -1) return;
  console.log('Un-requiring path', path);
  delete require.cache[path];
});
var objAfter = {};
objAfter.should    = 'should1';  // doesn't get assigned!
objAfter['should'] = 'should2';  // doesn't get assigned!
console.log('After:', objAfter);
// still has shouldJS stuff
console.log('objAfter.should:', objAfter.should);

它给出了:

Before: {}
Un-requiring path /my/path/node_modules/should/index.js
Un-requiring path /my/path/node_modules/should/lib/should.js
...
Un-requiring path /my/path/node_modules/should/lib/ext/contain.js
Un-requiring path /my/path/node_modules/should/lib/ext/promise.js
After: {}
objAfter.should: Assertion { obj: {}, anyOne: false, negate: false, params: { actual: {} } }

未分配任何.should属性。

有一种方法可以打开和关闭ShouldJS应该getter:

require('should');
(1).should.be.equal(1);
// turn off ShouldJS should getter
// and use should as a function
var should = require('should').noConflict();
should(0).be.equal(0);
// turn on ShouldJS should getter
should.extend();
require('should');
(1).should.be.equal(1);

以下是Readme官方的说法:

也可以在没有getter的情况下使用should.js(它甚至不会尝试扩展Object.protype),只需要require("should/as function")。或者,如果您已经使用了自动添加getter的版本,您可以调用.noConflict函数。

(某物)的结果。在大多数情况下,应该getter和应该(某物)是相同的

最新更新