Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

63
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?

7 months 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");
});
7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.