loganathan
loganathan

Reputation: 6176

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
    });
});

Upvotes: 11

Views: 19102

Answers (2)

stephenwil
stephenwil

Reputation: 534

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

Upvotes: 2

gunnx
gunnx

Reputation: 1209

You should inject the markup needed by your code

document.body.innerHTML = '<div id="test"><div class="panel-block"></div>....</div>'

Upvotes: 12

Related Questions