gpt4 book ai didi

karma-runner - 每次测试后如何让 karma 清除dom?

转载 作者:行者123 更新时间:2023-12-04 14:34:44 27 4
gpt4 key购买 nike

我正在测试的组件在 it() 测试中对 dom 进行了一些更改,但是它在下一个 it() 测试中仍然存在,这破坏了我的测试。有没有办法在每个 it() 测试中重置 DOM?

最佳答案

对于没有 JQUERY 的用户:

afterEach(function () {
document.body.innerHTML = '';
});

你也可以使用beforeEach,但我喜欢把它想象成一张餐 table ,你开始之前不清理,你自己清理之后

我写了一个小 DomCleaner,它在你的测试期间跟踪事件,并在清理时清理主体(requireJS,但你可以根据需要更改代码):
define(function () {
'use strict';

var installed = false,
documentAddListener,
documentListeners,
windowAddListener,
windowListeners;
return {
install: function () {
if (installed) {
throw new Error('Trying to install document cleaner, but its already installed!');
}
installed = true;
documentAddListener = document.addEventListener;
windowAddListener = window.addEventListener;
spyOn(document, 'addEventListener');
spyOn(window, 'addEventListener');
documentListeners = [];
windowListeners = [];
document.addEventListener.and.callFake(function () {
documentListeners.push(arguments);
documentAddListener.apply(null, arguments);
});
window.addEventListener.and.callFake(function () {
documentListeners.push(arguments);
windowAddListener.apply(null, arguments);
});
},
cleanup: function () {
if (!installed) {
throw new Error('Trying to cleanup document, but cleaner is not installed!');
}
installed = false;
documentListeners.forEach(function (listener) {
document.removeEventListener.apply(null, listener);
});
windowListeners.forEach(function (listener) {
window.removeEventListener.apply(null, listener);
});
documentListeners = [];
windowListeners = [];
document.body.innerHTML = '';
},
};
});

像这样使用它(在你的第一次描述中):
beforeEach(function () {
domCleaner.install();
});
afterEach(function () {
domCleaner.cleanup();
});

关于karma-runner - 每次测试后如何让 karma 清除dom?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36495295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com