Jest Test suite failed to run


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


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



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

 function selectElementContents(el) {
    var range = document.createRange();
    var sel = window.getSelection();

 export function copyText() {
    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() {
copyPasteText.addEventListener('click', copyText);


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"]');;

  const {baseNode} = document.getSelection();
  // Assert that the copyText function was called, and that the
  // text was copied as we'd expect it to.
  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:


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:


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