randombits randombits - 4 months ago 10
Node.js Question

shared functionality in mocha tests

I put the following code in its own file called

shared.js


afterEach(function () {
// insert code
});

var foo;

beforeEach(function () {
foo = {
bar: []
};
});

exports = module.exports = {};
exports.foo = foo;


I'd like the
afterEach
and
beforeEach
to be ran in every mocha.js test I have. so in each test file, I required
shared.js
.

The problem is it seems
foo
isn't available in the scope of my tests.
foo.bar
is undefined and inaccessible. The
beforeEach()
and
afterEach
hooks are running just fine, but I'm having trouble understanding how to properly export the scope of
foo
. This might be more of a Node.js problem than an actual Mocha problem.

Answer

The problem is that you can not modify the exported reference. In your case you are exporting undefined, because foo is uninitialized. If you initialize foo with an empty object and later try to reassign it to a different thing/object it will still not work because the exported reference is still the same.

The only thing you can do is modifying (mutating) the exported object like so:

afterEach(function () {
  // insert code 
});

var foo = {};

beforeEach(function () {
  foo.bar = [];
});

exports = module.exports = {};
exports.foo = foo;