2017-09-27 141 views
0

也有類似的問題,但似乎並沒有明確的答案,大多數答案都是舊的並且已被棄用。這就是爲什麼我問這個。將jQuery作爲依賴的Mocha測試模塊

所以我有這樣

// B2CPopup_methods_test.js 
import './domTestsHelper' 
import { expect } from 'chai' 
import newB2CPopup from './popupFromDbBoilerplate' 

describe('B2CPopup class method - ',() => { 
    const popup = newB2CPopup 

    it('prependHTMLToDOM prepends html to dom',() => { 
    popup.prependHTMLToDOM() 
    expect($('.b2cPopupOverlay')).to.exist 
    }) 
}) 

和我domTestsHelper.js測試看起來像這樣

import jquery from 'jquery' 
import jsdom from 'jsdom' 
import chai from 'chai' 
import chaiJquery from 'chai-jquery' 

// Set up testing environment to run like a browser in the command line 
const { JSDOM } = jsdom 
const { window } = new JSDOM('<!doctype html><html><body></body></html>') 
const $ = jquery(window) 

chaiJquery(chai, chai.util, $) 

export { $ } 

最後,我測試文件是

// B2CPopup.js 
import $ from 'jquery' 

export default class B2CPopup { 
    constructor ({ _id, options }, html) { 
    this._id = _id 
    this.options = options 
    this.html = html 
    } 

    start =() => {} 
    createOptions =() => {} 
    prependHTMLToDOM =() => $(this.html).prependTo('body') 

    show =() => {} 
} 

當然,我測試失敗,出現此錯誤

Error: jQuery requires a window with a document 

回答

0

在我domTestsHelper.js我添加了這些行

global.window = window 
global.document = window.document 
global.$ = $ 

我的最後文件看起來像這樣

import jquery from 'jquery' 
import jsdom from 'jsdom' 
import chai from 'chai' 
import chaiJquery from 'chai-jquery' 

// Set up testing environment to run like a browser in the command line 
const { JSDOM } = jsdom 
const { window } = new JSDOM('<!doctype html><html><body></body></html>') 
const $ = jquery(window) 

global.window = window 
global.document = window.document 
global.$ = $ 

chaiJquery(chai, chai.util, $)