如何使用 jsdom 测试带有“document”的功能

use*_*756 1 javascript mocha.js jsdom chai typescript

我有一个小问题..我正在尝试测试我创建的一些函数(用 Typescript 编写),并且我正在使用 mocha/chai/jsdom。现在,我在使用文档内的“文档”测试函数时遇到错误。我收到消息“ReferenceError:文档未定义”。我怎样才能用“文档”来测试这些功能?

例如:

[提示规格]

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)
  })
})
Run Code Online (Sandbox Code Playgroud)

[函数.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

}
Run Code Online (Sandbox Code Playgroud)

ver*_*tti 6

如果您提前准备好,则可以使 JSDOM 的文档可供您在全球范围内进行测试。

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;
Run Code Online (Sandbox Code Playgroud)

将其写入一个单独的文件,并将该文件作为参数添加到 mocha 的规范文件之前。就像是:

_mocha Specs/_setup.js Specs/*.js
Run Code Online (Sandbox Code Playgroud)