2017-08-29 165 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

一旦我回家,我會把它放在測試中!感謝您花時間回答。 –