[英]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#L102的cleanup
:
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)
}
它将做三件事:
container
内渲染的组件(默认为 HTML div
元素)HTML 元素。container
HTML 元素将从document.body
中删除。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.