I am writing some tests for a javascript API with mocha. I docker up my project before running the tests and I have realized that requiring a file to create an object in several tests, for example like these ones:
it('should return false 1', () => {
const testObject = require(./file.json)
delete testObject.neededAttribute1;
expect(function(testObject)).to.be.false;
});
it('should return false 2', () => {
const testObject = require(./file.json)
delete testObject.neededAttribute2;
expect(function(testObject)).to.be.false;
});
Javascript won't create the object testObject
in the second test, but use the first one with the changes previously made, making my tests unusable if I don't manually restore the object with whatever I have changed after the test has been executed.
I understand Javascript does this to be more efficient not loading the same file all the time, but just once.
But how can I make my tests in which I have a file with a correct object and I want to introduce small modifications one by one in each test?
Any ideas?
clone the object.
Import your object in a before function
https://futurestud.io/tutorials/mocha-global-setup-and-teardown-before-after
Then in each function or in beforeEach function, clone that object with something like lodash's cloneDeep function.