使用JSDOM加载现有的HTML文件以进行前端单元测试 [英] Loading existing HTML file with JSDOM for frontend unit testing

查看:134
本文介绍了使用JSDOM加载现有的HTML文件以进行前端单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是单元测试的新手,我知道我的测试可能没有价值,也没有遵循特定的最佳实践,但是我专注于使此工作正常进行,这将使我能够使用JSDOM测试前端代码

I'm new to unit testing, and I'm aware my tests may not be valuable or following a specific best practice, but I'm focused on getting this working, which will allow me to test my frontend code using 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正常运行.没有其他错误发生.任何帮助将不胜感激!

I'm getting the error "AssertionError: expected undefined to be an array". I'm simply using the array test as a test to ensure I have JSDOM functioning correctly. There are no other errors occurring. Any help would be much appreciated!

推荐答案

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

fromFile is an async function, meaning that by the time your beforeEach() has finished and the tests start running, it is (probably) still loading the file.

摩卡以两种方式处理异步代码:返回承诺或传递回调.因此,要么从fromFile返回诺言,要么执行以下操作:

Mocha handles async code in two ways: either return a promise or pass in a callback. So either return the promise from fromFile or do this:

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

promise版本如下:

The promise version looks like this:

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

这篇关于使用JSDOM加载现有的HTML文件以进行前端单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆