0

My node app has a fairly large test suite that depends on ShouldJS module. The problem is that the library blocks assigning .should properties on objects, but my test suite needs to spin up a server that needs to be mockable (i.e. run in the same process as my test suite) and dynamically build ElasticSearch queries, that need to set .should property on Objects.

I tried to un-require ShouldJS using an approach described here. But that didn't help - see example script below. Is there a workaround or an alternative approach?

Example:

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

which gives this:

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: {} } }

None of the .should properties are getting assigned.

Community
  • 1
  • 1
sakovias
  • 1,356
  • 1
  • 17
  • 26

1 Answers1

1

There's a way to turn ShouldJS should getter on and off:

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

Here's what the official Readme says:

It is also possible to use should.js without getter (it will not even try to extend Object.prototype), just require('should/as-function'). Or if you already use version that auto add getter, you can call .noConflict function.

Results of (something).should getter and should(something) in most situations are the same

sakovias
  • 1,356
  • 1
  • 17
  • 26