【问题标题】:How to properly call an init function in a ts class如何正确调用 ts 类中的 init 函数
【发布时间】: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


    【解决方案1】:

    我猜这是因为您在将 initSpy 附加到它之前创建 BrowserViewPreload 对象。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多