Reputation: 48440
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.
Upvotes: 0
Views: 1088
Reputation: 1591
If you want something that is specific to the context of each test, you can do something like the following:
afterEach(function () {
// insert code
});
beforeEach(function () {
this.foo = [];
});
exports = module.exports = {};
each test can then access its own this.foo
:
describe('myTest', function() {
it('should do something', function() {
this.foo.push("1"); // same 'this' as from beforeEach
// ...insert code
})
})
Upvotes: 0
Reputation: 4716
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;
Upvotes: 5