Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest can not deal with insertAdjacentElement?

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?

like image 699
RSeidelsohn Avatar asked Aug 23 '17 07:08

RSeidelsohn


1 Answers

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.

like image 91
RSeidelsohn Avatar answered Oct 19 '22 09:10

RSeidelsohn