我一直在撞墙而且为了我的生活,我无法弄清楚这个问题。我正在使用Jest(ts-jest)和默认的JSDOM进行测试。
在我的测试中,我分别为每个测试声明文档内容。例如。:
test('imageParentTest', () => {
document.body.innerHTML = '<div><img class="foo"></div>';
new HtmlElementsCheck()
// assertions for checking parent, returns <div>
})
在第一个规范中,一切都完美无缺。构造函数调用的方法返回一个document.querySelectorAll('.' + this._configuration.className);
节点的元素列表,我能够检查该列表,比较图像的父节点,并进行必要的操作。到现在为止还挺好。
如果我现在单独运行以下规范(imageParentTest2
),它也将正常工作,但是,如果我运行两个共享测试上下文的规范(所以如果我运行testContext
),imageParentTest2
规范不起作用,因为document.querySelectorAll('.' + this._configuration.className);
保持返回由imageParentTest
插入到正文中的元素列表。例如。
describe('testContext', () => {
test('imageParentTest', () => {
document.body.innerHTML = '<div><img class="foo"></div>';
new HtmlElementsCheck();
// assertions for checking parent, returns <div>
});
test('imageParentTest2', () => {
document.body.innerHTML = '<picture><img class="foo"></picture>';
new HtmlElementsCheck();
// assertions for checking parent, returns <div> when running test via 'testContext',
// returns <picture> when running test 'imageParentTest2' in isolation
})
})
我已经尝试过一个可以重置文档的解决方案,如this stack overflow answer中添加的那样
afterEach(() => {
document.getElementsByTagName('html')[0].innerHTML = '';
});
然而,在testContext
的开头,就我的理解而言,在我的情况下不应该是必要的,因为我在每次测试中都设置了document.body.innerHTML
。
我还尝试在jest.resetModules();
中添加一个beforeEach
,以确保实例化的类没有缓存,我已经尝试使用--no-cache
标志运行测试。
那么,在我的第二次测试中,document.querySelectorAll('.' + this._configuration.className);
类中的HtmlElementsCheck
如何返回第一次测试中插入体内的元素的节点列表?
编辑:我刚刚验证,类本身是一个单独测试中的新实例,无论我是单独运行它们还是通过上下文运行它们,所以它看起来越来越多,好像当我运行它们时身体不会以某种方式被覆盖在上下文中测试
好吧,所以似乎问题不在于文档本身被持久化,而是在beforeAll
中,它模拟了一个在我的类中执行的函数。由于这被嘲笑,我的第二个测试检测到模拟被第一次测试的参数调用。
所以模拟实际上导致了问题(即使第二个测试断言该函数没有被调用)。
更改要在beforeEach
中声明的模拟修复了该问题。