Ivan
Ivan

Reputation: 40778

Using a test runner to test functions that manipulate the DOM

I found out about end-to-end test runners for web applications quite recently. They basically replicate a user scenario from start to finish by literally running a web browser. There are for example NightwatchJS and TetsCafé.

There are also unit test runners like Mocha, Jasmine, AVA, Jest, QUnit. If I understand correctly they allow to test units of code like functions by comparing the returned value with the known result.

If I'm building a web application that involves handling document objects, i.e. appending and removing elements or changing their positions. Can I do this with the above five unit test runners? To me end-to-end tests runners seem to be more costly: I can't afford to run them as often as unit tests because they simply take more time.

So my question is, how can I test functions that interact with the DOM? I've found this page on Jest's wiki that explains how to test JQuery code. But I don't know how to test my own functions (no jQuery involved).

For example, I have a function that appends a new div to the body of the document and returns the newly created div element.

let add = function() {

  let div = createElement('div');
  div.innerHTML = '<div class="newElement">Hello World</div>';

  document.querySelector('body').appendChild(div)
  return div

}

How can I test that indeed:

Upvotes: 1

Views: 654

Answers (2)

PeterDanis
PeterDanis

Reputation: 9336

Jest uses jsdom as the default test environment, so the usual browser globals are accessible out of the box.

Please see https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string

Upvotes: 1

Ivan
Ivan

Reputation: 40778

I just found the solution testing some code. I didn't think it would work with Jest out of the box. We can actually access the DOM with document!

Here are the files:

add.js:

let add = function() {

    let div = document.createElement('div');
    div.innerHTML = '<div class="newElement">Hello World</div>';

    document.querySelector('body').appendChild(div)
    return div
}

module.exports = add;

add.test.js:

const add = require('./add');

test('add() returns a HTML element', () => {

    expect(add()).toBeInstanceOf(HTMLElement)

})


it('a() creates a div with class name newElement', () => {

    add()
    let textContent = document.querySelector('.newElement').textContent
    expect(textContent).toBe('Hello World')

})

Typing in the command line npm jest, it returns:

enter image description here

Does somebody know why this works? Is JestJS creating an empty document to test?

Upvotes: 0

Related Questions