Module variables not clear between tests in Jest

1k Views Asked by At

I would like to be able to isolate the side effects that seem to be related when testing two functions that modify the same state variable myVar independently of each other.

example.js

export function foobar() {
  sideEffect1();
  sideEffect2();
}

let myVar;

function sideEffect1() {
  if (myVar === undefined) {
    myVar = 'foo';
  }
}

function sideEffect2() {
  if (myVar === undefined) {
    myVar = 'bar';
  }
}

example.test.js

import example, {return2} from "../src/example";

test('Test Side Effect 1', () => {
  let se = example.__get__('sideEffect1');
  se();
  let myVar = example.__get__('myVar');
  expect(myVar).toBe("foo");
});


test('Test Side Effect 2', () => {
  let se = example.__get__('sideEffect2');
  se();
  let myVar = example.__get__('myVar');
  expect(myVar).toBe("bar");
});

Output

> jest "js/tests/example.test.js"

 FAIL  js/tests/example.test.js (6.056 s)
  ✓ Test Side Effect 1 (1 ms)
  ✕ Test Side Effect 2 (4 ms)

  ● Test Side Effect 2

    expect(received).toBe(expected) // Object.is equality

    Expected: "bar"
    Received: "foo"

      23 |   se();
      24 |   let myVar = example.__get__('myVar');
    > 25 |   expect(myVar).toBe("bar");
         |                 ^
      26 | });
      27 | 
      28 | 

If I run each test separately, both work ok. The problem seems to be when running the whole test suite. This is a simplification of the same problem that I have in a code that use in a more complex application. Any ideas why and how can it be solved?

babel.config.json

{
  "presets": ["@babel/preset-env"],
  "plugins": ["babel-plugin-rewire"]
}
1

There are 1 best solutions below

0
Seti On

Modules are loaded at the start of the execution and loaded as one - so yours example.js is executed properly, whichever function is executed first sideEffect1 or sideEffect2 this function sets the variable myVar and you then get this variable value