简体   繁体   中英

Loading existing HTML file with JSDOM for frontend unit testing

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM