我不太确定为什么组件的 DOM 编译在测试结束后仍然保留,但我注意到它只发生在最后运行的测试中。如果您可以添加另一个也编译组件但不添加全屏组件的组件测试,则前一个组件会被正确删除。因此,简单地添加更多测试可能是最简单的解决方案。
但如果这还不够,这里有两种可能的解决方案:
1. 不要编译它
如果您的测试不涉及验证生成的 DOM,您可以直接使用该组件来简化测试的安排。
describe('MyComponent', () => {
TestBed.configureTestingModule({
// declarations: [MyComponent],
imports: [
HttpClientTestingModule,
FormsModule,
RouterTestingModule.withRoutes([{ path: 'home', redirectTo: '/' }]),
],
// 1. Add the component as a provider.
providers: [MyComponent, SomeService1, SomeService2, { provide: SomeService3, useValue: {} }],
schemas: [NO_ERRORS_SCHEMA],
});
it('should do thing #1', () => {
// 2. Test it like you would test a service.
const comp = TestBed.get(MyComponent);
expect(comp.value).toBe(false, 'off at first');
comp.doThing1();
expect(comp.value).toBe(true, 'on after click');
comp.doThing1();
expect(comp.value).toBe(false, 'off after second click');
});
it('should do thing #2', () => {
const comp = TestBed.get(MyComponent);
expect(comp.value2).toMatch(/is off/i, 'off at first');
comp.doThing2();
expect(comp.value2).toMatch(/is on/i, 'on after clicked');
});
});
更多信息here https://angular.io/guide/testing#component-class-testing.
2.从DOM中删除它
如果您确实需要测试 DOM,我发现的唯一解决方法是在完成测试后显式删除 HTML 元素。
afterEach(() => {
if (fixture.nativeElement && 'remove' in fixture.nativeElement) {
(fixture.nativeElement as HTMLElement).remove();
}
});