2017-05-14 120 views
4

我試圖使用興農的模擬和間諜測試終極版組件和異步行動,但只要我導入興農到任何測試文件,運行以下NPM腳本:設置JSDOM與摩卡

mocha --require test/helpers/browser.js --compilers .:babel-core/register --opts test/client/**/*.{js,jsx} --recursive test/client

我得到以下錯誤:

var div = typeof document !== "undefined" && document.createElement("div"); 
                ^

TypeError: document.createElement is not a function at .../node_modules/sinon/lib/sinon/util/core/deep-equal.js:3:55

browser.js是我設置JSDOM:

import { JSDOM } from 'jsdom'; 

const doc = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>'); 
cost win = doc.defaultView; // tried doc.window; 

global.document = doc; 
global.window = win; 

/* 
Object.keys(win).forEach(property => { 
    if (typeof global[property] === 'undefined') { 
    global[property] = win[property]; 
    } 
}); 
*/ 

global.navigator = { 
    userAgent: 'node.js' 
}; 

我想我沒有正確設置jsdom?我試圖尋找了一圈,發現在browser.js註釋代碼文件之上,但它產生的錯誤,當去掉註釋:

Object.keys(win).forEach(function (property) { 
    ^

TypeError: Cannot convert undefined or null to object.

回答

13

documentwindow一個屬性,而不是倒過來:

const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>'); 

global.window = dom.window; 
global.document = dom.window.document; 
+1

謝謝,這個修好了! – mythereal