Mocking `document` in jest

后端 未结 8 1384
我在风中等你
我在风中等你 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:23

    I have resolved this using setUpFiles property in jest. This will execute after jsdom and before each test which is perfect for me.

    Set setupFiles, in Jest config, e.g.:

    "setupFiles": ["/browserMock.js"]
    
    
    // browserMock.js
    Object.defineProperty(document, 'currentScript', {
      value: document.createElement('script'),
    });
    

    Ideal situation would be loading webcomponents.js to polyfill the jsdom.

提交回复
热议问题