在真实浏览器中运行 Jasmine 时,我注意到 TestBed
fixture 组件没有在 DOM 中被销毁,并且在测试结束后仍然存在:
这是一个经过测试的组件:
@Component({
selector: 'test-app',
template: `<div>Test</div>`,
})
class Test {}
还有一个测试(plunk)。
let component;
let fixture;
let element;
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [Test],
})
.compileComponents();
fixture = TestBed.createComponent(Test);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.css('div')).nativeElement;
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
it('should compile Test', () => {
expect(element).toBeTruthy();
});
为什么 Test
组件实例没有从 DOM 中删除,应该如何解决?
为什么要将 fixture 组件添加到 DOM 中?它们可以像 AngularJS 中的 $rootElement
那样从 DOM 中分离出来吗?
最佳答案
Jasmine 和 Angular 都不会自动删除它,也许是为了帮助您获得有关测试执行的更多详细信息。
要删除它,您只需使用 afterEach(...)
,比如:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
element = debugElement.nativeElement;
});
afterEach(() => {
document.body.removeChild(element);
});
对于非 Angular 用户:
afterEach(() => {
document.body.innerHTML = '';
});
Above clears all default
<script>
tags, but that does not matter (because they did already run, and Karma does never refresh the browser, at least not till all tests finish).
关于javascript - 在 Jasmine 测试期间,Angular 4 fixture 组件持续存在于 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645662/