Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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";

beforeEach(async () => {
  jest.resetModules();
});

test("first", async () => {
  const { getFoo } = await import("./foo.js");
  expect(getFoo()).toBe("foo");
});

test("second", async () => {
  const { getFoo } = await import("./foo.js");
  expect(getFoo()).toBe("foo");
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!