I have a lib.js
that I will require and test in 2 tests, test1.js
and test2.js
(using mocha and should.js):
lib.js
simply exports a data object:
module.exports.data = {};
test1.js
looks like this:
var data = require('./lib.js').data;
describe('.data', function() {
it('should be able to add data', function() {
data.entry = 'random data';
console.log(data); // expecting to get `{ entry: 'random data' }`
})
})
And test2.js
looks like this:
var data = require('./lib.js').data;
describe('.data', function() {
it('should have empty data', function() {
console.log(data); // expecting to get `{}`
})
})
If I run mocha with multiple files, like mocha test1.js test2.js
, both would print { entry: 'random data' }
, and it would be undesired that running tests together gets different results from running them separately.
I believe this is because of node caching the modules, and I could restore the module before leaving the test. However, since this behavior might happen easily when writing tests, I wonder what the correct strategy is. Maybe there is something I can do on the Mocha level? Thanks a lot!
I use node-clone to create a deep copy of a required module beforeEach
test. Now the tests will use the clone instead of the cached module.
var clone = require('clone');
describe('config', function(){
var data;
beforeEach(function() {
data = clone(require('./lib.js')).data;
});
it('should be able to add data', function() {
data.entry = 'random data';
console.log(data); // expecting to get `{ entry: 'random data' }`
})
it('should have empty data', function() {
console.log(data); // expecting to get `{}`
})
});
If you don't use a before
or beforeEach
hooks you should be able to do the same across multiple files by cloning as soon as possible in each test script.
var clone = require('clone'),
data = clone(require('./lib.js')).data;