Loading existing HTML file with JSDOM for frontend unit testing

Deadly 提交于 2019-12-06 09:09:45

问题


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

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!


回答1:


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.

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

The promise version looks like this:

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


来源:https://stackoverflow.com/questions/45945798/loading-existing-html-file-with-jsdom-for-frontend-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!