Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clear encapsulated value in imported module – Jest js

Let’s say I’m importing to Jest module like:

let var;

export const getVar = () => {
    if(var == null) {
        var =  Date.now()
    }

    return var;
}

I am trying to make unit tests for this module, however, on every unit test I have to reset the "var" value. I’ve tried to redefine the module using require on "beforeEach" method but it does not work. Does anyone know how to reset encapsulated values like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using old require syntax and resetModules

foo.js

let foo;

const getFoo = () => {
  if (!foo) {
    foo = "foo";
  } else {
    foo = "bar";
  }
  return foo;
};

module.exports = { getFoo };

foo.test.js

beforeEach(() => jest.resetModules());

test("first", () => {
  const { getFoo } = require("./foo");
  expect(getFoo()).toBe("foo");
});

test("second", () => {
  const { getFoo } = require("./foo");
  expect(getFoo()).toBe("foo");
});

Using dynamic import and resetModules

foo.js

let foo;

export const getFoo = () => {
  if (!foo) {
    foo = "foo";
  } else {
    foo = "bar";
  }
  return foo;
};

foo.test.js

import { jest } from "@jest/globals";
let getFoo;

beforeEach(async () => {
  jest.resetModules();
  const { getFoo: getFooAlias } = await import("./foo.js");
  getFoo = getFooAlias;
});

test("first", () => {
  expect(getFoo()).toBe("foo");
});

test("second", () => {
  expect(getFoo()).toBe("foo");
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading