I have a service with 2 properties:
Service
...
public usernameAnnounced;
private username: Subject<string> = new Subject<string>();
constructor() {
super();
this.usernameAnnounced = this.username.asObservable();
}
On my component I want to subscribe to the property:
Component
public ngOnInit(): void {
this.service.usernameAnnounced.subscribe((username: string) => {
this.username = NavbarComponent.capitalizeFirstLetter(username);
});
}
I emit to the username on another comp. but its irrelevant for this question.
Now I want to mock usernameAnnounced but I have difficulties with it. I tried it with spyOn
and it throws me a: 'usernameAnnounced is not a function.'
with spyOnProperties
it throws me a : 'property is not a getter'.
Tested comp.
so far my approach looks as follows:
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}`);
});
Does someone has any hints?