Skip to main content

Writing Unit Tests for DOM Manipulation

In this tutorial, we will show you how to write unit tests for DOM manipulation using the Jest testing framework and the jsdom library.

Setting up Jest and jsdom

To set up Jest and jsdom, follow these steps:

  1. Create a new project folder and navigate to it in your terminal.

  2. Initialize a new npm project with the following command:

npm init -y
  1. Install Jest and jsdom as development dependencies with the following command:
npm install --save-dev jest jsdom
  1. Add a new test script to your package.json file:
"scripts": {
"test": "jest"

Writing the DOM manipulation function

First, let's create a simple DOM manipulation function that we want to test. Create a new file called domManipulation.js in your project folder, and add the following code:

function changeBackgroundColor(element, color) {
if (element && color) { = color;
return true;
return false;

module.exports = changeBackgroundColor;

This function accepts an HTML element and a color as arguments and sets the background color of the given element to the specified color.

Writing the unit tests

Next, create a new file called domManipulation.test.js in your project folder, and add the following code:

const { JSDOM } = require('jsdom');
const changeBackgroundColor = require('./domManipulation');

describe('changeBackgroundColor', () => {
let dom;
let element;

beforeEach(() => {
dom = new JSDOM('<!DOCTYPE html><div id="target"></div>');
element = dom.window.document.getElementById('target');

it('should change the background color of the element', () => {
changeBackgroundColor(element, 'red');

it('should return true when the background color is changed', () => {
const result = changeBackgroundColor(element, 'blue');

it('should return false when the background color is not changed', () => {
const result = changeBackgroundColor(null, 'green');

In this test file, we import JSDOM from the jsdom library and the changeBackgroundColor function we want to test. We then create a new JSDOM instance and a target element in the beforeEach function, which is executed before each test case. Finally, we write three test cases to test the functionality of the changeBackgroundColor function.

Running the tests

To run the tests, execute the following command in your terminal:

npm test

Jest will automatically discover and run the test file, and you should see the test results in your terminal.

Writing unit tests for DOM manipulation using Jest and jsdom helps ensure that your code behaves as expected and makes it easier to identify and fix bugs. This practice also encourages you to write modular, testable code, which can lead to better overall code quality.