Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest global variables that persist

Tags:

jestjs

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?

like image 365
cham Avatar asked Feb 02 '18 02:02

cham


2 Answers

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.

  1. Create globalSetup in config with following file:

     // setup.js
     module.exports = async () => {
       process.env.TEST_VAR = "my-test-var";
     };
    
  2. 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();
     });
     // ...
    
  3. 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.

like image 179
kingofsevens Avatar answered Oct 21 '22 06:10

kingofsevens


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.

like image 35
stijndepestel Avatar answered Oct 21 '22 05:10

stijndepestel