【发布时间】:2020-05-05 02:10:49
【问题描述】:
我正在为一个班级写一些测试。在我的测试中,如果我不调用 browserViewPreload.init(),则测试会失败,但是当我调用 browserViewPreload.init() 时,它会通过。
既然我已经在 beforeEach 块中完成了测试,为什么还需要在测试中显式调用 browserViewPreload.init()?
//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();
});
});
【问题讨论】:
标签: javascript mocking jestjs