Table of contents
1.
Introduction
2.
What is DOM
2.1.
Example DOM
2.1.1.
index.html
2.1.2.
script.js
3.
Testing
3.1.
Introduction to  JSDOM
3.1.1.
Installing Jsdom
3.1.2.
Jsdom Test Environment
3.1.3.
Output
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Jest DOM Manipulation

Author Aditya Anand
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome readers! In this blog, we will learn jest and the DOM. When you interact with the browser, you will interact with the DOM, Document Object Module. Codes that manipulate the DOM are another class of function that is often considered challenging to test. We cannot use the browser at the time of testing DOM. So to test DOM, we need test runners like karma. Alternatively, we can also use Jest with jsdom to achieve the same result. Jsdom is a package to interact with DOM within node.js.

Let's get started, and I hope you learn a lot from this tutorial.

What is DOM

The DOM (Document Object Model) is the data representation of the objects, which consists of the structure and content of a document on the web.

The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

A web page is a document that can be either displayed in the browser window or as the HTML source. DOM representation allows it to be manipulated in a program with a scripting language such as JavaScript as an object-oriented representation of the web page.

The HTML DOM model is constructed as a tree of Objects.

Example DOM

Let’s create an example DOM to test.

index.html

<html>
  <body>
    <input id="newTodoInput" />
    <button id="addTodoBtn">Add todo</button>
    <ol id="todoList"></ol>
    <script type="text/javascript" src="./script.js"></script>
  </body>
</html>

This is what it will look like when running in the browser.

script.js

const addTodo = () => {
    const newTodoInput = document.getElementById('newTodoInput');
    let currentTodoList = document.getElementById('todoList').innerHTML;
    currentTodoList += `<li>${newTodoInput.value}</li>`;
    document.getElementById('todoList').innerHTML = currentTodoList;
    newTodoInput.value = '';
  }
document.getElementById('addTodoBtn').addEventListener('click', addTodo);

Testing

Now that our example is ready let’s try to test. For that, create a test file called index.test.js. We will write our test script in this file.

In the test file, we will create a custom DOM using jsdom, which will be only that part of our main DOM that we are testing.  

Introduction to  JSDOM

Writing tests for a UI is complex. jsdom comes in the picture here. JSDOM is a library. Just like a browser, it parses and interacts with assembled HTML. Jsdom is not actually a browser. Instead, it implements web standards as browsers do.

You can pass some HTML in Jsdom, and it will parse it as a browser do, and then you can modify it using DOM APIs or inspect it.

Installing Jsdom

To install jsdom, run the following command in the terminal.

npm install jsdom

Jsdom Test Environment

By default, jest uses the node testEnvironment. This essentially makes any tests meant for a browser environment invalid.

jsdom implements a browser environment that supports these types of UI tests.

To configure the jsdom test environment, write the following configuration in jestConfig.json. If you are unfamiliar with Jest Configuration, I highly recommend checking out the Jest Configuration blog.

{
    "testEnvironment": "jsdom"
}

Sample jestConfig.json with current configuration will look like this.

{
    "testEnvironment": "jsdom",
    "watchPlugins": ["./custom-watch-plugin.js"],
    "collectCoverage": false,
    "coverageThreshold": {
    "global": {
      "branches": 50,
      "functions": 100,
      "lines": 85
    },
    "./function.js": {
        "branches": 50,
        "functions": 100,
        "lines": 85,
        "statements": -10
        }
    },
    "testTimeout": 300,
    "globals": {
    "globalVar": "a global variable"
    },
    "snapshotFormat": {
    "printBasicPrototype": false
    }
}


Index.test.js
We are ready to write our test code to test DOM manipulations.
test('Check addTodo function is able add todo to todoList', () => {
    document.body.innerHTML = `
      <input id="newTodoInput" />
      <button id="addTodoBtn">Add todo</button>
      <ol id="todoList"></ol>
    `;
    require('./script.js');
 
    const newTodoInput = document.getElementById('newTodoInput');
    const addTodoBtn = document.getElementById('addTodoBtn');
    const todolist = document.getElementById('todoList');
 
    newTodoInput.value = 'welcome to coding ninjas!';
    addTodoBtn.click();
 
    expect(todolist.innerHTML).toBe('<li>welcome to coding ninjas!</li>');
  });

Let’s understand what’s going on here. So in the test function, we are first creating a custom DOM, which is only that part of our main DOM that we want to test.

We require the script file to modify the custom DOM next.

Then we are adding a value to the input field since we are not in the browser at the time of testing, so we are giving in the test file itself. We call the “click” event listener, which will eventually call the addTodo function in script.js, modifying our custom DOM.

We expect the new modified custom DOM to match the expected value in the next step.

Output

.

FAQs

  1. How does Jest test within a DOM environment?
    Jest ships with jsdom, which simulates a DOM environment as if you were in a browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser.
     
  2. What is Jest DOM?
    Jest-dom is a companion library for Testing Library that provides custom DOM element matches for Jest.
     
  3. Does Jest run in the browser?
    No, you cannot run jest tests in a browser environment out of the box. Using Jsdom, you can access all of the various DOM APIs in the test file.
     
  4. What is a test Dome?
    TestDome is a service that helps you screen job candidates using automated work-sample tests.

Key Takeaways

We have learned that DOM manipulation is significant and complicated to test. We can use Jest with jsdom for this purpose. Using jsdom. We will create a custom DOM in the test file

simulating the browser. Now we can test any DOM manipulation without the need for UI.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass