Mocking `document` in jest

后端 未结 8 1378
我在风中等你
我在风中等你 2020-11-29 04:12

I\'m trying to write tests for my web components projects in jest. I already use babel with es2015 preset. I\'m facing an issue while loading the js file. I have followed a

8条回答
  •  失恋的感觉
    2020-11-29 04:27

    I have been struggling with mocking document for a project I am on. I am calling document.querySelector() inside a React component and need to make sure it is working right. Ultimately this is what worked for me:

    it('should test something', () => {
        const spyFunc = jest.fn();
        Object.defineProperty(global.document, 'querySelector', { value: spyFunc });
        
        expect(spyFunc).toHaveBeenCalled()
    });
    

提交回复
热议问题