由于我在 Angular 应用程序的单元测试中启用了 css 样式,因此每次显示来自 ngx-bootstrap 的模态的组件时,即使在该特定组件的单元测试完成运行后,它仍保留在浏览器中。
这使得很难直观地检查其他测试的执行情况和测试结果:
由于我在 Angular 应用程序的单元测试中启用了 css 样式,因此每次显示来自 ngx-bootstrap 的模态的组件时,即使在该特定组件的单元测试完成运行后,它仍保留在浏览器中。
这使得很难直观地检查其他测试的执行情况和测试结果:
更新:为 ngx-bootstrap 6+ 更新代码,旧版本见下文
解决方案是确保在每次运行可能显示模态的代码的测试之后隐藏模态:
import { BsModalService } from 'ngx-bootstrap';
// test definitions ...
afterEach(() => {
const modalService: BsModalService = TestBed.get(BsModalService);
modalService.hide();
});
该技术使用BsModalService中的hide()方法。
我发现拥有一个可以在测试中重用的实用程序函数很有用:
export function closeModalsAfterEach() {
afterEach(() => {
const modalService: BsModalService = TestBed.get(BsModalService);
modalService.hide();
});
}
ngx-bootstrap 5 之前的旧工作解决方案
import { BsModalService } from 'ngx-bootstrap';
// test definitions ...
afterEach(() => {
const modalService: BsModalService = TestBed.get(BsModalService);
modalService.hide(1);
});
export function closeModalsAfterEach(upToLevel: number = 1) {
afterEach(() => {
const modalService: BsModalService = TestBed.get(BsModalService);
for (let level = 1; level <= upToLevel; level++) {
modalService.hide(level);
}
});
}
您可以将其从 DOM 中删除
afterEach(() => {
// const modalService: BsModalService = TestBed.get(BsModalService);
// modalService.hide(1);
const htmlCollection = document.getElementsByTagName('modal-container');
if (htmlCollection.length > 0 && htmlCollection[0] != null)
htmlCollection[0].remove();
});