I see that global variables can be specified across Jest tests but that:
mutation will not be persisted across test runs for other test files.
Is there way to make changes to global variables that persist across all test files?
You can use Environment Variables
to carry those variables across tests, even if you have multiple test files. Official docs states below that any global variable cannot be accessed through tests:
Note: Any global variables that are defined through globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.
But the tests use the same environment so you can set and change variables accordingly.
Create globalSetup
in config with following file:
// setup.js
module.exports = async () => {
process.env.TEST_VAR = "my-test-var";
};
You can use this variable in your tests:
// my-test.js
// ...
it("should read the test var from environment", async (done) => {
expect(process.env.TEST_VAR).toEqual("my-test-var");
process.env.TEST_VAR = "new-var";
expect(process.env.TEST_VAR).toEqual("new-var");
done();
});
// ...
You can unset this variable ones the test are complete with globalTeardown
config with the following file:
// teardown.js
module.exports = async () => {
delete process.env.TEST_VAR;
};
Remember that setting and not properly using environment variables are risky that may alter your test results. I use it to pass around a persistent variable.
I do not think there is a way to do that. I also do not think there should be a way to do this. Test cases should be able to run independently from one another. Allowing some mutation to a global variable to be persisted across all test files might create a situation in which a test case will only succeed if it is run after another test case has mutated some variable. This situation might result in very fragile tests and should be avoided.
If you need a global variable (or any other variable for that matter) to be in a certain state for a test to succeed. You should look into the setup and teardown methods of Jest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With