使用JSDOM加载现有HTML文件以进行前端单元测试

时间:2017-08-29 18:13:58

标签: javascript unit-testing mocha chai jsdom

我是单位测试的新手,我知道我的测试可能没有价值或遵循特定的最佳做法,但我专注于让这项工作正常运行,这将使我能够使用JSDOM测试我的前端代码。

const { JSDOM } = require('jsdom');
const { describe, it, beforeEach } = require('mocha');
const { expect } = require('chai');

let checkboxes;
const options = {
  contentType: 'text/html',
};

describe('component.js', () => {
  beforeEach(() => {
    JSDOM.fromFile('/Users/johnsoct/Dropbox/Development/andybeverlyschool/dist/individual.html', options).then((dom) => {
      checkboxes = dom.window.document.querySelectorAll('.checkbox');
    });
  });
  describe('checkboxes', () => {
    it('Checkboxes should be an array', () => {
      expect(checkboxes).to.be.a('array');
    });
  });
});

我收到错误" AssertionError:期望未定义为数组"。我只是使用数组测试作为测试来确保我正确运行JSDOM。没有其他错误发生。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

fromFile 是一个异步函数,意味着由你的 beforeEach()完成并且测试开始运行时,它(可能)仍在加载文件。





Mocha以两种方式处理异步代码:返回一个promise或传递一个回调。所以要么从 fromFile 返回promise,要么执行以下操作:




  beforeEach(function(done){
 JSDOM.fromFile (myFile)
 .then((dom)=> {
 checkboxes = dom.window.document.querySelectorAll('。checkbox');
})
 .then(完成,完成);
});
  




承诺版本如下所示:


 

  beforeEach(function(){
 return JSDOM.fromFile(myFile)
 .then((dom)=> {
 checkboxes = dom.window .document.querySelectorAll('。checkbox');
});
});