繁体   English   中英

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

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

每次测试后,我想重置document.body ,因为我在document.body上添加了一些类。 我的印象是反应测试库会在每次测试后重置它,但似乎它正在重用document ,因为在使用debug时,在上一个测试中添加的类在下一个测试中仍然可见。

RTL 的清理function 不会清除 HTML 元素的className属性。 请参阅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)
}

它将做三件事:

  1. 卸载在container内渲染的组件(默认为 HTML div元素)HTML 元素。
  2. container HTML 元素将从document.body中删除。
  3. mountedContainers JS Set中删除。

因此,如果您想在document.body元素处重置/恢复className ,则需要自己完成。 afterEach() / afterAll()钩子是正确的地方。

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

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

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

JSDOM 创建的document.body元素只有一个。 所以不要认为 RTL 会在运行每个测试用例之前创建一个document.body并在使用render function 时在每次测试之后清理它。 render function 将创建一个container

暂无
暂无

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

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