简体   繁体   English

运行测试 React 测试库后重置 document.body

[英]Reset document.body after running test React Testing Library

After each test, I would like to reset the document.body since I am adding some classes on document.body .每次测试后,我想重置document.body ,因为我在document.body上添加了一些类。 I was under the impression that react testing library would reset it after each test, but it seems that it is reusing the document since classes added in the previous test are still visible in the next test when using debug .我的印象是反应测试库会在每次测试后重置它,但似乎它正在重用document ,因为在使用debug时,在上一个测试中添加的类在下一个测试中仍然可见。

RTL's cleanup function will not clear the HTML element className attribute. RTL 的清理function 不会清除 HTML 元素的className属性。 See v12.1.5/src/pure.js#L102 of cleanup :请参阅v12.1.5/src/pure.js#L102cleanup

function cleanup() {
  mountedContainers.forEach(cleanupAtContainer)
}

// maybe one day we'll expose this (perhaps even as a utility returned by render).
// but let's wait until someone asks for it.
function cleanupAtContainer(container) {
  act(() => {
    ReactDOM.unmountComponentAtNode(container)
  })
  if (container.parentNode === document.body) {
    document.body.removeChild(container)
  }
  mountedContainers.delete(container)
}

It will do three things:它将做三件事:

  1. Unmount the component rendered inside the container (the HTML div element by default) HTML element.卸载在container内渲染的组件(默认为 HTML div元素)HTML 元素。
  2. The container HTML element will be removed from document.body . container HTML 元素将从document.body中删除。
  3. Deleted from the mountedContainers JS Set .mountedContainers JS Set中删除。

So if you want to reset/restore the className at document.body element, you need to do it by yourself.因此,如果您想在document.body元素处重置/恢复className ,则需要自己完成。 The afterEach() / afterAll() hooks is the right place to do it. afterEach() / afterAll()钩子是正确的地方。

afterEach(() => {
  document.body.className = '';
});

test('t-1', () => {
  document.body.className = 'test-1';
  //...
});

test('t-1', () => {
  document.body.className = 'test-2';
  //...
});

There is only one document.body element created by JSDOM. JSDOM 创建的document.body元素只有一个。 So don't think RTL will create a document.body before running each test case and clean it up after each test when using the render function.所以不要认为 RTL 会在运行每个测试用例之前创建一个document.body并在使用render function 时在每次测试之后清理它。 The render function will create a container . render function 将创建一个container

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM