Testing with Jest: Awesome Tips and Tricks

In this blog post I will discuss some tips and trics about the JEST framework.

Jest Internally used JSDOM . ** JSDOM** is a library which parses and interacts with assembled HTML just like a browser. The benefit to JSDOM is that it isn’t actually a browser. Instead, it implements web standards like browsers do. You can feed it some HTML, and it will parse that HTML.

So if you want to mock any window/document variables then those variables are provided by jsdom by default which let’s us to mock them using built-in jest methods jest.spyOn().mockImplementation() and restore with .mockRestore().

For example,Let’s suppose you have following javascript function in your code

const TestModule = (function() {
    const notification = () => {
        window.alert("DO SOME WORK")
    };
    return {
        notification: notification,
    };
})();
module.exports = TestModule;

In the above code snippet I am using window.alert. Now if you want to write the unit test for the above function you have to mock the window.alert function.

You can mock any global object in two way

using Object.definePoperty

Object.defineProperty(global, "window", {
    value: {
        alert: jest.fn()
    }
});

using jest.spyOn

est.spyOn(window, 'alert').mockImplementation(() => {});
const TestModule = require("../module");
describe("Mock window property", () => {
    it("should mock window alert function", () => {
        Object.defineProperty(global, "window", {
            value: {
                alert: jest.fn(),
            },
        });
        TestModule.notification();
        expect(window.alert).toBeCalled();
    });
});

output

Mock window property
√ should mock window alert function (3 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s

-----------|---------|----------|---------|---------|-------------------

All files | 100 | 100 | 100 | 100 |

module.js | 100 | 100 | 100 | 100 |

-----------|---------|----------|---------|---------|-------------------

Test Suites: 1 passed, 1 total

Tests: 1 passed, 1 total

Snapshots: 0 total

Time: 4.225 s

Ran all test suites.

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post