Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Creating a Fake DOM to test in a JavaScript test suite

The problem

  • TypeError: Cannot set property 'innerHTML' of null

The question

I am using Jest to handle my JavaScript's unit test and it brings embedded jsdom, which should to handle the DOM-related subjects.

This is my fragment of test: jest.dontMock ('fs');

var markup = require ('fs')
  .readFileSync(__dirname + '/markup/index.html')
  .toString();

describe ('my app', function () {
  it ('should initialize adding <h1> to the DOM', function () {
    document.documentElement.innerHtml = markup;

    app.start();

    expect(app.DOM).toEqual('<h1>Hello world!</h1>');
  });
});

The implementation of .start() has within:

document.querySelector('h1').innerHTML = 'Hello world';

When running the library in browser, it works well. But when testing via CLI, it don't.

Diagnostics

Basically, I tried the following:

 it ('should initialize adding <h1> to the DOM', function () {
    document.documentElement.innerHtml = markup;

    console.log(document.querySelector('h1'));

    // [...]
  });

And the console.log() outputs 'null' — seems like the markup I created isn't being added to the "DOM" that jsdom created.

This is the content of /markup/index.html, also the same as markup variable:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Linguisticjs Markup Test</title>
</head>
<body>
  <h1>Bonjour le monde !</h1>
  <h3>Comment ça va ?</h3>
</body>
</html>

Any ideas?

Upvotes: 0

Views: 1973

Answers (1)

Louis
Louis

Reputation: 151401

It's a typo. This is wrong:

document.documentElement.innerHtml

It should be innerHTML. The way you are doing it is creating a field named innerHtml but does not have for effect to create DOM nodes.

Upvotes: 2

Related Questions