How to test DOM manipulation in JEST

loganathan picture loganathan · May 19, 2017 · Viewed 14.3k times · Source

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

Answer

gunnx picture gunnx · Jun 26, 2017

You should inject the markup needed by your code

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