Chr*_*son 4 javascript unit-testing mocha.js jsdom chai
我是单元测试的新手,我知道我的测试可能没有价值或没有遵循特定的最佳实践,但我专注于让它工作,这将允许我使用 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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
我收到错误“AssertionError:预期未定义为数组”。我只是使用数组测试作为测试,以确保 JSDOM 正常运行。没有其他错误发生。任何帮助将非常感激!
fromFile是一个异步函数,这意味着当您beforeEach()完成并开始运行测试时,它(可能)仍在加载文件。
Mocha以两种方式处理异步代码:返回承诺或传入回调。因此,要么返回承诺,fromFile要么这样做:
beforeEach(function(done) {
JSDOM.fromFile(myFile)
.then((dom) => {
checkboxes = dom.window.document.querySelectorAll('.checkbox');
})
.then(done, done);
});
Run Code Online (Sandbox Code Playgroud)
承诺版本如下所示:
beforeEach(function() {
return JSDOM.fromFile(myFile)
.then((dom) => {
checkboxes = dom.window.document.querySelectorAll('.checkbox');
});
});
Run Code Online (Sandbox Code Playgroud)