Context:
I am using Hapi Lab to run a bunch of tests.
I also have an additional set of files that export mock JSON data.
What's the issue:
Each of the tests manipulate the JSON files as part of their routine.
The first test always passes, because it's dealing with the 'clean' JSON data, whereas following tests sometimes fail because the previous test(s) modified the JSON when the previous test(s) ran.
Similarly, if I run tests specifically one file at a time, the output is fine. Whereas if I attempt to test a directory that contains multiple tests, I get failures due to the malformed JSON.
npm run lab /test-directory/test1.js // Works fine
npm run lab /test-directory/test2.js // Works fine
vs
npm run lab /test-directory //Fails
What's the question:
Is there a convenient way of getting Lab to 'restore' the original state between tests instead of allowing the same instance of JSON data to leak between different tests?
I found that a convenient workaround for this issue was to run each test in its own worker using node child processes.
I added a file run-tests-sequentially.js
which calls the tests in turn:
const { promisify } = require('util');
const { exec } = require('child_process');
const execAsync = promisify(exec);
(async () => {
console.log('Running test1...');
const { stdout: test1Output } = await execAsync('npm run test:integration /test-directory/test1.js');
console.log('Completed test1...');
console.log(test1Output);
console.log('Running test2...');
const { stdout: test2Output } = await execAsync('npm run test:integration /test-directory/test2.js');
console.log('Completed test2...');
console.log(test2Output);
})();
I then called node ./run-tests-sequentially.js
to run the sequence.
Each test ran in a 'clean' worker, with no data leaks.