【问题标题】:how to use jsdom to test functions with 'document'如何使用 jsdom 测试带有 'document' 的函数
【发布时间】:2017-07-25 18:47:22
【问题描述】:

我有一个小问题.. 我正在尝试测试我创建的一些函数(用 Typescript 编写),并且我正在使用 mocha/chai/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)
  })
})

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

}

【问题讨论】:

  • 应该是 doc.querySelector 吗?我看到您在正文中定义 doc 的位置,但我没有看到任何地方定义的文档,即使在全局中也是如此。

标签: javascript typescript mocha.js chai jsdom


【解决方案1】:

如果您提前准备好 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,就在您的规范文件之前。比如:

_mocha Specs/_setup.js Specs/*.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多