Jest is a widely used testing framework that internally utilizes JSDOM. JSDOM is a library that parses and interacts with HTML similar to a browser. It implements web standards and allows mocking of window/document variables using Jest’s built-in methods like jest.spyOn().mockImplementation()
and restoration with .mockRestore()
.
In this blog post, we will explore how to mock window/document variables in Jest to facilitate unit testing.
Mocking Window/Document Variables
Let’s consider an example where we have a JavaScript function that utilizes window.alert
:
const TestModule = (function() {
const notification = () => {
window.alert("DO SOME WORK");
};
return {
notification: notification,
};
})();
module.exports = TestModule;
To unit test this function, we need to mock the window.alert
function. There are two ways to achieve this:
1. Using Object.defineProperty:
We can mock global objects like window
using Object.defineProperty
:
Object.defineProperty(global, "window", {
value: {
alert: jest.fn()
}
});
2. Using jest.spyOn:
Another approach is to use jest.spyOn
to mock the window.alert
function:
jest.spyOn(window, 'alert').mockImplementation(() => {});
const TestModule = require("../module");
describe("Mocking window property", () => {
it("should mock the 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.
The above test case verifies that the window.alert
function is called when invoking TestModule.notification()
. It achieves this by mocking the window
object and asserting the window.alert
function’s invocation.
Conclusion
In this blog post, we explored some tips and tricks for mocking window/document variables in the Jest testing framework. By utilizing Object.defineProperty
or jest.spyOn
, we can effectively mock global objects like window
to facilitate unit testing. This capability enhances the testing process by enabling us to control and verify the behavior of code that interacts with browser-specific variables.
Remember to adapt the provided examples to match your specific testing requirements.