Search code examples
javascriptvariablesjestjsglobal-variables

Can global scope variables be re-initialized to their original values in JavaScript after being modified for testing in Jest?


I am running some tests using Jest. I have defined some variables. Some tests will modify the variables, for example, adding an item to an array. After each test, I want to variables to reset to the values that they were originally assigned to, so each test has the original data to work with. Is this possible? Does Jest have a solution to this?

For example

import * as matchers from "jest-extended";
expect.extend(matchers);

const array = [1, 2, 3];

const addFour = array => array.push(4);

const addFive = array => array.push(5);

describe("tests", () => {
  it("should add 4 to the array", () => {
    addFour(array);
    expect(array).toHaveLength(4);
  });

  //array should be [1, 2, 3, 4]

  it("should add 5 to the array", () => {
    addFive(array);
    expect(array).toHaveLength(4);
  });
  //array should be [1, 2, 3, 5] and not [1, 2, 3, 4, 5]
});


I have edited the problem to better resemble my test case. The issue has been resolved. Please see below.


Solution

  • You could use the beforeEach function of Jest to initialize the variable.

    let array;
    
    beforeEach(() => {
        array = [1, 2, 3];
    });
    

    However in your example the addFour and addFive methods are non-mutating, meaning they won't change the value of the array variable. In this case there's no need to reset the value of the array because it never changes.