Does Jest reset the JSDOM document after every suite or test?

天涯浪子 提交于 2019-12-03 12:30:22

To correct the (misleading) accepted answer and explicitly underline that very important bit of information from one of the previous comments:

No. Jest does not clean the JSDOM document after each test run! It only clears the DOM after all tests inside an entire file are completed.

That means that you have to manually cleanup your resources created during a test, after every single test run. Otherwise it will cause shared state, which results in very subtle errors that can be incredibly hard to track.

The following is a very simple, yet effective method to cleanup the JSDOM after each single test inside a jest test suite:

describe('my test suite', () => {
  afterEach(() => {
    document.getElementsByTagName('html')[0].innerHTML = ''; 
  });

  // your tests here ...
});

Rico Pfaus is right, though I found that resetting the innerHTML the way he suggests was too destructive and caused tests to fail. Instead, I found selecting a specific element (by class or id) I want to remove from the document more effective.

describe('my test suite', () => {
    afterEach(() => {
        document.querySelector(SOME CLASS OR ID).innerHTML = ''
    })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!