下面是一个典型的代码,显示所有组件通用的错误消息
<div>
<div>
<app-alert></app-alert>
</div>
<div>
<router-outlet></router-outlet>
</div>
</div>
当组件出现错误时,消息将显示在<app-alert>
标签内
但是使用TestBed
渲染的组件不会渲染该标签
使用AlertComponent
类和AlertService
类为<app-alert>
标签提供服务
AlertService
通过构造函数作为私有注入
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent {
constructor(private alertService: AlertService) { }
}
参考角度测试基础知识,fixture.debugElement
不会给出<app-alert>
标签,原因是标签在router-outlet
之外
我将如何测试登录失败以及在login.component.spec.ts
中显示消息invalid credentials
您可以在.spec.ts
文件中创建一个包含这两个组件的TestHost组件。
@Component({
template: `
<app-alert></app-alert>
<login></login>
`
})
class TestHostComponent {
}
.....
TestBed.configureTestingModule({
declarations: [AppAlertComponent, LoginComponent, TestHostComponent],
providers: [/* your providers */]
})
fixture = TestBed.createComponent(TestHostComponent);
testHost = fixture.componentInstance;
// get a handle on the login component/class
loginComponent = fixture.debugElement.query(By.directive(LoginComponent)).componentInstance;
// get a handle on the app alert component/class
alertComponent = fixture.debugElement.query(By.directive(AppAlertComponent)).componentInstance;
通过这种设置,login
和app-alert
都将被绘制,您可以测试它们是如何协同工作的。
我想我解释的不止这个链接,但它也应该有帮助。