Jest can not deal with insertAdjacentElement?
Asked Answered
H

1

9

I want to test a quite simple JS function

export function displaySpinner() {
    const loadingOverlayDOM = document.createElement('DIV');
    const spinner           = document.createElement('IMG');

    loadingOverlayDOM.id        = 'overlay-spinner';
    loadingOverlayDOM.className = 'content-overlay';
    spinner.className           = 'is-spinning';
    spinner.setAttribute('src', '/assets/img/svg/icons/spinner.svg');
l   loadingOverlayDOM.insertAdjacentElement('beforeend', spinner);
    document.body.insertAdjacentElement('beforeend', loadingOverlayDOM);
}

with this (for the purpose of this issue stripped down) Jest test code:

test('displaySpinner displays the spinner overlay in the current page', () => {
    utils.displaySpinner();
});

But the test run yells at me:

FAIL  app/helper/utils.test.js
● utils › displaySpinner displays the spinner overlay in the current page

TypeError: loadingOverlayDOM.insertAdjacentElement is not a function

  at Object.displaySpinner (app/helper/utils.js:185:439)
  at Object.<anonymous> (app/helper/utils.test.js:87:15)
  at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
  at process._tickCallback (internal/process/next_tick.js:109:7)

Is this an error in Jest or am I missing something here?

Homeopathic answered 23/8, 2017 at 7:31 Comment(0)
H
16

I finally found the answer myself:

Jest uses jsdom which does not yet support the DOM function insertAdjacentElement (see this issue on GitHub and it's references). So I'll have to wait until jsdom implements it or use another method in my JS.

You can replace the default version of jsdom with an up-to-date version (e.g. 14) by installing the corresponding module:

npm install --save-dev jest-environment-jsdom-fourteen

or using yarn:

yarn add jest-environment-jsdom-fourteen --dev

and then using the jest testEnvironment config parameter:

{
  "testEnvironment": "jest-environment-jsdom-fourteen"
}

Note that if you launch jest with the --env=jsdom argument, this will override the config file, so you need to remove it.

Homeopathic answered 23/8, 2017 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.