具有jQuery作为依赖关系的Mocha Test模块

时间:2017-09-27 12:01:28

标签: javascript jquery mocha jsdom

有类似的问题,但似乎没有明确的答案,大多数答案都是旧的并且已弃用。这就是为什么我问这个。

所以我有这样的测试

size_t quality;

我的setImageCompressionQuality看起来像这样

// 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 { $ }

2 个答案:

答案 0 :(得分: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, $)

答案 1 :(得分:0)

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")
  });
});