每次测试后,我想重置 document.body
,因为我在 document.body
上添加了一些类。我的印象是 react 测试库会在每次测试后重置它,但它似乎正在重用 document
因为在使用 时在下一个测试中在上一个测试中添加的类仍然可见>调试
。
最佳答案
RTL cleanup函数不会清除 HTML 元素 className
属性。请参阅v12.1.5/src/pure.js#L102 清理
:
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
内渲染的组件(默认情况下为 HTMLdiv
元素)HTML 元素。 container
HTML 元素将从document.body
中删除。- 已从
mountedContainers
中删除JS设置
。
因此,如果您想重置/恢复 document.body
元素中的 className
,您需要自己完成。 afterEach()
/afterAll()
Hook 是执行此操作的正确位置。
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
函数时在每次测试后清理它。 render
函数将创建一个容器
。
关于javascript - 运行测试后重置 document.body React 测试库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73581220/