Я пишу несколько тестов для класса. В моих тестах, если я не вызываю browserViewPreload.init()
, тест не пройден, но когда я вызываю browserViewPreload.init()
, он проходит.
Почему мне нужно явно вызывать browserViewPreload.init()
в тесте, когда я уже сделал это в моем блоке beforeEach?
//myFile.ts
export default class BrowserViewPreload {
constructor(){
this.init();
}
attachMouse(){
console.log('attaching mouse')
}
init(){
return document.addEventListener('DOMContentLoaded', this.attachMouse)
}
}
//myFile.spec.ts
import BrowserViewPreload from './browserViewPreload'
function bootStrapComponent() {
return new BrowserViewPreload();
};
describe('BrowserViewPreload Class', () => {
var browserViewPreload;
let initSpy
let docspy
let mouseSpy
beforeEach(()=>{
browserViewPreload = bootStrapComponent();
initSpy = jest.spyOn(browserViewPreload, 'init')
docspy = jest.spyOn(document, 'addEventListener')
})
it('should report name', () => {
//browserViewPreload.init(); not including this makes the tests fail. Why do I need to make the call here when I've already done so in the beforeEach
expect(initSpy).toHaveBeenCalled();
expect(docspy).toHaveBeenCalled();
document.dispatchEvent(new Event('DOMContentLoaded'));
expect(mouseSpy).toHaveBeenCalled();
});
});