2017-08-29 166 views
1

我是新来的单元测试,我知道我的测试可能没有价值或遵循特定的最佳实践,但我专注于获得这项工作,将允许我使用JSDOM测试我的前端代码。使用JSDOM加载现有的HTML文件进行前端单元测试

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正常运行。没有其他错误发生。任何帮助将非常感激!

+0

我的问题缩小到 - beforeEach还没有结束之前我复选框试运行。 –

回答

1

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

Mocha handles async code有两种方式:返回一个承诺或传入回调。所以,无论是从fromFile回报承诺或做到这一点:

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

的承诺版本是这样的:

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

一旦我回家,我会把它放在测试中!感谢您花时间回答。 –