Jest 是否在每个套件或测试后重置 JSDOM 文档? [英] Does Jest reset the JSDOM document after every suite or test?

查看:17
本文介绍了Jest 是否在每个套件或测试后重置 JSDOM 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一些组件,这些组件在挂载和卸载时会超出其 DOM 结构,以提供否则无法实现的特定交互功能.

I'm testing a couple of components that reach outside of their DOM structure when mounting and unmounting to provide specific interaction capability that wouldn't be possible otherwise.

我使用 Jest 和默认的 JSDOM 初始化在 node.js 中创建类似浏览器的环境.我在文档中找不到任何建议 Jest 在每次测试执行后重置 JSDOM 的内容,如果不是这种情况,也没有关于如何手动执行此操作的明确文档.

I'm using Jest and the default JSDOM initialization to create a browser-like environment within node. I couldn't find anything in the documentation to suggest that Jest reset JSDOM after every test execution, and there's no explicit documentation on how to do that manually if that is not the case.

我的问题是,Jest 是在每次测试、套件之后重置 JSDOM 实例,还是在所有测试运行中都保留一个 JSDOM 实例?如果是这样,我该如何控制?

My question is, does Jest reset the JSDOM instance after every test, suite or does it keep a single instance of JSDOM across all test runs? If so, how can I control it?

推荐答案

为了更正(误导性的)已接受的答案,并明确强调来自先前评论之一的非常重要的信息:

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

没有.Jest 不会在每次测试运行后清理 JSDOM 文档!它只在整个文件中的所有测试完成后清除 DOM.

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.

以下是一种非常简单但有效的方法,用于在 jest 测试套件中的每次测试后清理 JSDOM:

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 ...
});

这篇关于Jest 是否在每个套件或测试后重置 JSDOM 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆