要在Angular 11中进行组件测试,有时需要在测试中渲染组件,但此时组件可能在路由出口外呈现。这可能会导致测试失败。解决此问题的一种方法是使用Angular的TestBed模块的overrideComponent方法来重写组件的模板,并将其包含在一个包含RouterTestingModule的测试模块中。
下面是一个示例代码,展示如何通过测试工具链来测试组件:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture
beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [AppComponent, TestComponent], imports: [RouterTestingModule.withRoutes([ { path: 'test', component: TestComponent } ])] }).compileComponents(); }));
beforeEach(() => { fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should create the app', () => { expect(component).toBeTruthy(); });
it('should render test component', () => { const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('app-test')).toBeTruthy(); }); });
在这个例子中,我们新建了一个测试模块,并将其作为依赖项注入到应用组件中。我们还定义了一个测试组件,并将其用作路由中的目标。最后,我们可以在测试代码中渲染应用组件,并验证它是否包含了TestComponent组件。
此方法可以帮助我们轻松地测试我们的组件,无需担心它们是否在路由出口中呈现。