如何使用jsdom测试函数与'文档'

如何使用jsdom测试函数与'文档'

问题描述:

我有一个小问题..我想测试我创建的一些函数(用Typescript编写),并且我正在使用mocha/chai/jsdom。现在,我在用文档内的'document'测试函数时出错。我得到'ReferenceError:document is not defined'消息。我怎么还能用这个'文档'来测试这些函数呢?如何使用jsdom测试函数与'文档'

例如:

[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 

} 
+0

它应该是doc.querySelector?我知道你在哪里定义了文档,但是我没有在任何地方看到文档,即使在全球范围内。 – veratti

可以提供给您的测试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; 

写到一个单独的文件和你的规范文件前添加该文件作为参数传递给摩卡。喜欢的东西:

_mocha Specs/_setup.js Specs/*.js