我有一项具有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);
});
}
我将另一个组合发送给用户名。但是与这个问题无关。
现在,我想模拟usernameAnnounced,但遇到困难。我用spyOn
进行了尝试,结果是:“ usernameAnnounced不是函数”。
与spyOnProperties
一起使用时,它会抛出:“财产不是吸气剂”。
到目前为止,我的方法如下:
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}`);
});
有人有什么提示吗?
答案 0 :(得分:4)
我想出了解决方案: 首先创建一个像这样的jasmine.spyObj:
const authenticationMock: AuthenticationService = jasmine.createSpyObj('AuthenticationService',
['usernameAnnounced']);
将其分配给模拟服务:{provide: AuthenticationService, useValue: authenticationMock}
。
而且,单元测试本身只是为您的属性分配了预期的结果:
const spy = TestBed.get(AuthenticationService);
spy.usernameAnnounced = Observable.of('dummyUser');
答案 1 :(得分:1)
我总是必须在我的模拟游戏上建立一个主题(或BehaviorSubject)。
$http.get()
热烈的问候