下面是一个典型的代码,显示所有组件共有的错误信息
<div>
<div>
<app-alert></app-alert>
</div>
<div>
<router-outlet></router-outlet>
</div>
</div>
当组件出现错误时,消息将显示在 <app-alert>
标签内
但是使用 TestBed
呈现的组件不会呈现该标签
<app-alert>
标签使用 AlertComponent
类和 AlertService
类
AlertService
通过构造函数作为私有注入
@Component({ templateUrl: 'login.component.html' })
export class LoginComponent {
constructor(private alertService: AlertService) { }
}
参考 Angular Testing Basics fixture.debugElement
不会给出 <app-alert>
标签,原因是该标签在 router-outlet
之外
我将如何测试登录失败并在 invalid credentials
内显示消息 login.component.spec.ts
答案 0 :(得分:1)
您可以创建一个 TestHost 组件,将它们都包含在您的 .spec.ts
文件中。
@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
都将被绘制,您可以测试它们如何协同工作。
我想我解释的比这个 link 多一点,但它应该也有帮助。