how to use jsdom to test functions with 'document'

会有一股神秘感。 提交于 2021-02-11 15:43:59

问题


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

}

回答1:


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


来源:https://stackoverflow.com/questions/45311337/how-to-use-jsdom-to-test-functions-with-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!