Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a module mock between tests in same test suite in Jest?

I've mocked some nodejs modules (one of them, for example, is fs). I have them in a __mocks__ folder (same level als node_modules) folder and the module mocking works. However, whichever "between test clearing" option I use, the next test is not "sandboxed". What is going wrong here?

A very simplified example of the mocked fs module is:

// __mocks__/fs.js
module.exports = {
    existsSync: jest.fn()
        .mockReturnValueOnce(1)
        .mockReturnValueOnce(2)
        .mockReturnValueOnce(3) 
}

I'm simply expecting that in every test, whenever init() is called (see below), existsSync starts again at value 1: the first value of jest.fn().mockReturnValue(). In the testfile I have the following structure:

// init.test.js
const init = require("../init");
const { existsSync } = require("fs");
jest.mock("fs");

describe("initializes script", () => {
    afterEach(() => {
        // see below!
    });    

    test("it checks for a package.json in current directory", () => {
        init();
    });

    test("it stops script if there's a package.json in dir", () => {
        init(); // should be run in clean environment!
    });
}

And once again very simplified, the init.js file

const { existsSync } = require("fs");
console.log("value of mocked response : ", existsSync())

I'm getting the following results for existsSync() after the first and second run ofinit() respectively when I run in afterEach():

  • jest.resetModules() : 1, 2
  • existsSync.mockReset(): 1, undefined
  • existsSync.mockClear(): 1, 2
  • existsSync.mockRestore(): 1, undefined

Somebody know what I'am doing wrong? How do I clear module mock between tests in the same suite? I'll glady clarify if necessary. Thanks!

like image 996
axm__ Avatar asked Sep 28 '18 18:09

axm__


People also ask

How do you reset mock Before each test Jest?

afterEach(() => { jest. clearAllMocks(); }); to call jest. clearAllMocks to clear all mocks after each test.

Which method is useful to clean up a mock's usage data between two assertions?

results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

How do you reset Jest spyOn?

To reset or clear a spy in Jest, we call jest. clearAllMocks . For instance, we write: afterEach(() => { jest.


1 Answers

Reset the modules and require them again for each test:

describe("initializes script", () => {
    afterEach(() => {
        jest.resetModules() 
    });    

    beforeEach(() => {
        jest.mock("fs");
    })

    test("it checks for a package.json in current directory", () => {
        const init = require("../init");
        init();
    });

    test("it stops script if there's a package.json in dir", () => {
        const init = require("../init");
        init();
    });
}
like image 75
Alexandre Borela Avatar answered Oct 20 '22 00:10

Alexandre Borela