Jest Test suite failed to run


#1

Rather than running my tests, jest is finding so-called errors in my index.js file.

 FAIL  __tests__/index.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'addEventListener' of null

      22 |
      23 | copyButton.addEventListener('click', function() {
    > 24 | 	copyText();
      25 | 	copyButton.focus();
      26 | });
      27 | copyPasteText.addEventListener('click', copyText);

      at Object.<anonymous> (js/index.js:24:12)
      at Object.<anonymous> (__tests__/index.test.js:3:14)

In a browser my code is fine.

My setup is npm script and vanilla js.

In my package.json I have

  "scripts": {
    "test": "jest"
  },

which I am running from command line.

I have my test code in a file called index.test.js


#2

Can you share the code for both index.js and index.test.js please?


#3

index.js:

var copyButton = document.querySelector('[data-component="copypaste-button"]');
var copyPasteText = document.querySelector('[data-component="copypaste-text"]');

 function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
	sel.addRange(range);
	console.log(range);
}

 export function copyText() {
	selectElementContents(copyPasteText);
    document.execCommand('copy');
    document.querySelector('.c-copypaste__button svg').classList.add('opacity1');
       setTimeout(function() {
         document.querySelector('.c-copypaste__button svg').classList.remove('opacity1');
       }, 700); 
}

copyButton.addEventListener('click', function() {
	copyText();
	copyButton.focus();
});
copyPasteText.addEventListener('click', copyText);

index.test.js

import copyText from '../js/index.js';

test('component copies the text', () => {

  document.body.innerHTML =
    `<button data-component="copypaste-button" value="copy"></button>
      <div data-component="copypaste-text">My text</div>`;

  // Emulate a click on our button
  const copyButton = document.querySelector('[data-component="copypaste-button"]');
  copyButton.click();

  const {baseNode} = document.getSelection();
  // Assert that the copyText function was called, and that the
  // text was copied as we'd expect it to.
  expect(copyText).toBeCalled();
  expect(baseNode.nodeValue).toEqual('My text');
});

This is my first time writing a javascript test and using jest so the code might be total garbage :rolling_eyes:


#4

I don't think you're mocking up your test data correctly and I don't think you can use document like this, from within a test itself. You should use setupFiles.

Or possibly before/beforeEach:


#5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.