2017-07-25 107 views
0

我有一個小問題..我想測試我創建的一些函數(用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

回答

2

可以提供給您的測試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 
相關問題