What is jest-environment-jsdom?
The jest-environment-jsdom package is a custom environment for Jest that allows you to simulate a browser-like environment using jsdom. This is useful for testing web applications without running them in an actual browser. It provides a simulated DOM API that you can interact with in your tests.
What are jest-environment-jsdom's main functionalities?
Simulating browser environment for testing
This feature allows you to simulate browser-like interactions such as clicking a button and then asserting the expected outcome, all within a Node.js environment.
test('simulates a click event', () => {
document.body.innerHTML = '<button id="button">Click me</button>';
const button = document.getElementById('button');
button.addEventListener('click', () => {
button.innerHTML = 'Clicked';
});
button.click();
expect(button.innerHTML).toBe('Clicked');
});
Testing DOM manipulation
You can test DOM manipulation by creating, modifying, and removing elements, and then asserting that these changes have taken place as expected.
test('adds a new div to the body', () => {
const div = document.createElement('div');
div.id = 'new-div';
document.body.appendChild(div);
expect(document.getElementById('new-div')).not.toBeNull();
});
Mocking global variables
The package allows you to mock global variables such as localStorage, which is useful for testing code that interacts with browser APIs that are not available in Node.js.
test('mocks a global variable', () => {
global.localStorage = {
getItem: jest.fn().mockReturnValue('mockValue')
};
expect(global.localStorage.getItem('key')).toBe('mockValue');
});
Other packages similar to jest-environment-jsdom
jest-environment-node
This package is similar to jest-environment-jsdom but is intended for testing Node.js applications. It does not simulate a browser environment and is therefore not suitable for testing browser-specific code.
karma
Karma is a test runner that works with any framework and allows you to run tests in real browsers. Unlike jest-environment-jsdom, which simulates a browser environment, Karma actually runs tests in real browsers, which can be more accurate but also slower and more complex to set up.
mocha-jsdom
This package integrates jsdom with Mocha, another testing framework. It provides similar functionality to jest-environment-jsdom but is designed to work with Mocha instead of Jest.
enzyme
Enzyme is a testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output. It can be used in conjunction with jest-environment-jsdom to test React components in a simulated browser environment.