Loading existing HTML file with JSDOM for frontend

2020-06-27 06:11发布

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条回答
够拽才男人
2楼-- · 2020-06-27 06:49

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');
    });
});
查看更多
登录 后发表回答