问题描述
我有一个小问题..我正在尝试测试我创建的某些功能(以Typescript编写),并且正在使用mocha/chai/jsdom.现在,在测试文档中带有文档"的功能时遇到错误.我收到消息"ReferenceError:未定义文档".我怎么仍然可以在其中带有文档"的情况下测试这些功能?
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?
例如:
[prompt.spec.ts]
[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]
[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
}
推荐答案
如果事先准备好,则可以使JSDOM的文档在全球范围内可供您的测试使用.
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;
将此文件写入一个单独的文件中,然后将该文件作为参数添加到mocha中,紧接您的spec文件之前.像这样:
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
这篇关于如何使用jsdom测试带有“文档"的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!