具有 jQuery 作为依赖项的 Mocha 测试模块

Mocha Test modules which have jQuery as a dependency

还有类似的问题,但似乎没有明确的答案,而且大多数答案都过时且已弃用。这就是我问这个的原因。

所以我有这样的测试

// 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

在我的 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, $)
const
  expect = require('chai').expect,

  // extarnal js files | files to test ..
  demoJs = require("../src/JS/demo.js"),

  //jsdom stuff
  jsdom = require('jsdom'),
  { JSDOM } = jsdom,
  doc = new JSDOM(),

  //jquery stuff
  jquery = require('jquery')
;

// setting $ to global
$ = global.jQuery = require('jquery')(doc.window);


describe('jQuery : jsdom testing ', () => {
  it('testing if jquery can access a p element', () => {
    expect($("<p>hi</p>").text()).to.equal("hi")
    expect($("<p>hola</p>").text()).to.equal("hola")
  });
});