Jest DOM Manipulation

Jest DOM Manipulation

If you're a developer, you might have come across the term "DOM Manipulation". In simple words, it is the process of changing the HTML document structure using JavaScript. Jest is a popular testing framework that can be used to test DOM manipulation functions.

Method 1: Using Jest's built-in functions

Jest provides built-in functions that can be used to test DOM manipulation functions. These functions include:

  • .toBeInTheDocument() - This function checks if an element is present in the document.
  • .toHaveTextContent() - This function checks if an element contains a specific text.
  • .toHaveAttribute() - This function checks if an element has a specific attribute.
  • .toHaveClass() - This function checks if an element has a specific class.

Here's an example of how to use these functions:


  import { getByTestId } from '@testing-library/dom';

  test('test DOM manipulation function', () => {
    const container = document.createElement('div');
    container.innerHTML = '<input data-testid="input-element" type="text" />';
    const input = getByTestId(container, 'input-element');

    expect(input).toBeInTheDocument();
    expect(input).toHaveAttribute('type', 'text');
    expect(input).not.toHaveClass('some-class');
  });

Method 2: Using Vanilla JS

You can also test DOM manipulation functions using Vanilla JS. Here's an example:


  test('test DOM manipulation function', () => {
    const container = document.createElement('div');
    container.innerHTML = '<input data-testid="input-element" type="text" />';
    const input = container.querySelector('[data-testid="input-element"]');

    expect(input).toBeTruthy();
    expect(input.getAttribute('type')).toBe('text');
    expect(input.classList.contains('some-class')).toBeFalsy();
  });

In this example, we used Vanilla JS to create a container and add an input element to it. We then used the querySelector() method to select the input element and test its attributes using Vanilla JS.

Both of these methods are valid ways to test DOM manipulation functions with Jest. It's up to you to decide which one works better for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe