Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test DOM manipulation in JEST

I'm trying to test a ES6 function which updates the dom element whenever it is being executed. Currently I'm getting empty nodelist since the HTML page is not loaded. What is approach to test this purely with JEST?

jest.dontMock('../scripts/taskModel');
import Request from '../__mocks__/request';
import Task from '../scripts/taskModel';

describe('taskModel', () => {
    it('Should initialize with no friends items', function() {
        expect(document.querySelectorAll('.panel-block').length).toBe(1); // THIS IS ALWAYS RETURNS EMPTY NODELIST
        var task = new Task();
        task.index();
        expect(document.querySelectorAll('.panel-block').length).toBeGreaterThanOrEqual(6); // THIS IS ALWAYS RETURNS EMPTY NODELIST
    });
});
like image 367
loganathan Avatar asked May 19 '17 06:05

loganathan


People also ask

How DOM is tested with Jest?

Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser! So we can very easy to simulates a DOM environment when use Jest, get start install Jest and write test case!

What is DOM manipulation technique?

An exploration into the HTMLElement type These documents are static, they do not change. The Document Object Model (DOM) is a programming interface implemented by browsers in order to make static websites functional. The DOM API can be used to change the document structure, style, and content.

Does Jest use Jsdom?

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.


1 Answers

A reminder that if the dataset property is being used by the JS under test, then because jsdom doesn't (yet) support the dataset attribute, there is a handy polyfill, which will also insert DOM content for you - https://www.npmjs.com/package/jsdom-mount

like image 176
stephenwil Avatar answered Sep 22 '22 12:09

stephenwil