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

标签 javascript unit-testing mocha.js chai jsdom

我是单元测试的新手,我知道我的测试可能没有值(value)或没有遵循特定的最佳实践,但我专注于让它正常工作,这将允许我使用 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 正常运行的测试。没有其他错误发生。任何帮助将不胜感激!

最佳答案

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

Mocha handles async code有两种方式:返回 promise 或传入回调。因此,要么从 fromFile 返回 promise ,要么这样做:

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

promise 版本如下所示:

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

关于javascript - 使用 JSDOM 加载现有的 HTML 文件以进行前端单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945798/

相关文章:

javascript - 按类对元素进行编号并获取特定 div 的位置

c# - 断言数组在 Visual Studio 2008 测试框架中是相等的

node.js - chai.assert.isRejected 消息验证器不起作用

ruby-on-rails - 使用 Mocha 测试函数是否被调用

javascript - Angularjs、Typescript、Uglify 无法实例化模块 myApp .... 未知提供者 : a

c# - 如何从 .cs 文件调用 JavaScript/jQuery 函数 (C#)

c# - 如何模拟返回 Task<IList<>> 的方法?

unit-testing - 不要模拟域对象规则?

node.js - 用另一个函数替换一个函数进行测试

javascript - 处理IE浏览器的关闭按钮