【发布时间】:2018-12-13 23:01:28
【问题描述】:
我有一个具有 2 个属性的服务:
服务
...
public usernameAnnounced;
private username: Subject<string> = new Subject<string>();
constructor() {
super();
this.usernameAnnounced = this.username.asObservable();
}
在我的组件上我想订阅该属性:
组件
public ngOnInit(): void {
this.service.usernameAnnounced.subscribe((username: string) => {
this.username = NavbarComponent.capitalizeFirstLetter(username);
});
}
我向另一个 comp 上的用户名发出。但它与这个问题无关。
现在我想模拟 usernameAnnounced 但我遇到了困难。我用spyOn 尝试了它,它给我一个提示:'usernameAnnounced 不是一个函数。
使用spyOnProperties,它会抛出一个:'property is not a getter'。
经过测试的比较
到目前为止,我的方法如下:
beforeEach(async(() => {
TestBed.configureTestingModule({
...
declarations: [NavbarComponent],
providers: [
...,
{provide: service, useValue: authenticationMock}
]
})
.compileComponents();
fixture = TestBed.createComponent(NavbarComponent);
}));
...
it('should render username',() => {
const underTest = fixture.componentInstance;
spyOnProperty(authenticationMock, 'usernameAnnounced').and.returnValue({
subscribe: () => {'boboUser'}}); <== important part here
underTest.ngOnInit();
fixture.detectChanges();
const compiled: HTMLElement = fixture.debugElement.nativeElement.querySelector('#userName');
const rendered: string = compiled.textContent;
expect(rendered).toMatch(`Logged in as: ${underTest.username}`);
});
有人有什么提示吗?
【问题讨论】:
标签: angular typescript jasmine karma-jasmine jasmine2.0