user1806756
user1806756

Reputation: 145

how to use jsdom to test functions with 'document'

I have a small question.. I am trying to test some functions I created (written in Typescript), and I am using mocha/chai/jsdom. Now, I get an error while testing functions with 'document' inside the document.. I get the message 'ReferenceError: document is not defined'. How can I still test these functions with 'document' in it?

For example:

[prompt.spec.ts]

import { expect } from 'chai'
import { JSDOM } from 'jsdom'
import { functionX } from './functions'

describe('Functions', () => {
  it('is possible to execute functionX with simple parameters', () => {
    const jsdom = new JSDOM()
    const htmlElement = jsdom.window.document.createElement('div')
    expect(functionX(htmlElement, function() { return true; } )).to.equal(true)
  })
})

[functions.ts]

export const functionX = (
    body:HTMLElement, callback: (ok: boolean) => void
) => {
    const doc = body.ownerDocument
    const parent = doc.body

    // ...

    let container = document.querySelector('.container') as HTMLDivElement  //  ReferenceError: document is not defined

}

Upvotes: 1

Views: 4378

Answers (1)

veratti
veratti

Reputation: 570

You can make the JSDOM's document available to your tests globally if you prepare it in advance.

import { JSDOM } from 'jsdom';
const { window } = new JSDOM('<!doctype html><html><body></body></html>');

// Save these two objects in the global space so that libraries/tests
// can hook into them, using the above doc definition.
global.document = window.document;
global.window = window;

Write this into a separate file and add that file as a parameter to mocha right before your spec files. Something like:

_mocha Specs/_setup.js Specs/*.js

Upvotes: 6

Related Questions