2016-09-18 106 views
1

我想使用sinon的假服務器來模擬一個摩卡測試中的jQuery調用。但測試總是給出一個錯誤,如jQuery.post不是一個函數或jQuery未定義。我不清楚如何使用es6/es2015語法將jQuery導入到jsdom中。設置jQuery測試與jsdom,摩卡,es2016

這是測試/ setup.js的內容(安裝一個jquery NPM封裝)

import { jsdom } from 'jsdom'; 
import jQuery from 'jquery'; 

var exposedProperties = ['window', 'navigator', 'document']; 

global.document = jsdom(''); 

global.window = document.defaultView 
Object.keys(document.defaultView).forEach((property) => { 
    if (typeof global[property] === 'undefined') { 
    exposedProperties.push(property); 
    global[property] = document.defaultView[property]; 
    } 
}); 

global.jQuery = jQuery; 

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

我假定安裝固定後,我應該只能夠在測試中使用jQuery.post()而不改變有。

大部分設置的配置是從http://airbnb.io/enzyme/docs/guides/jsdom.html

回答

0

未來當你加載了jQuery,它檢測到的全球空間是否是一個窗口。如果是,那麼它將自身輸出到窗口jQuery$。如果不是,那麼它作爲模塊值導出的內容是安裝函數,您可以在未來的窗口對象上安裝jQuery。在你原來的代碼中,到了時間import jQuery from 'jquery';,jQuery沒有窗口可供使用,所以你得到一個安裝函數,你必須使用它來在窗口上安裝jQuery,一旦你有了它。

下面是可用的代碼。我添加或修改的每條線都被評論。

import { jsdom } from 'jsdom'; 
import _jQuery from 'jquery'; // Modify this to add the underscore. 

var exposedProperties = ['window', 'navigator', 'document']; 

global.document = jsdom(''); 

global.window = document.defaultView 

const jQuery = _jQuery(window); // Add this line. 

Object.keys(document.defaultView).forEach((property) => { 
    if (typeof global[property] === 'undefined') { 
    exposedProperties.push(property); 
    global[property] = document.defaultView[property]; 
    } 
}); 

global.jQuery = jQuery; 

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

// This should output "function". 
console.log(typeof jQuery.post);