1

I have a function that produces side effect. I am simplifying it to log the content of a Node element to keep the focus in the issues.

logFile.js

function log() {
  console.log(document.querySelector('#mydiv').textContent)
}

export { log }

Then I have the unit test

log.test.js

import {
  log
} from '../logFile'

import { JSDOM } from 'jsdom'

describe('Test log function', () => {

  it('should log what the div is holding', () => {
    const dom = new JSDOM(`<!DOCTYPE html><div id="mydiv">HELLO</div>`);
    const document = dom.window.document;

    // This works
    console.log(document.querySelector('#mydiv').textContent)

    // This also works
    console.log(document.querySelector('#mydiv').textContent)

    // This doesn't work
    log()
  });
})

This is a trivial example, but, what happens if I want to manipulate the DOM, using .appendChild() ...?

And in the console I see the following error

    TypeError: Cannot read property 'textContent' of null

      26 |   
    > 27 |   console.log(document.querySelector('#mydiv').textContent)
         |               ^
      28 |
      29 | }

Anyone can help me? Thanks

Peter
  • 2,004
  • 2
  • 24
  • 57
  • It won't work because `log` refers to `document` global, while you're creating local JSDOM. Add an element to existing Jest DOM, https://jestjs.io/docs/en/tutorial-jquery – Estus Flask Feb 19 '21 at 08:26

0 Answers0