I have a service with 2 properties:
...
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:
    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'.
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?
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
fakeAsynclinkWraps a function to be executed in the fakeAsync zone: Microtasks are manually executed by calling flushMicrotasks() . Timers are synchronous; tick() simulates the asynchronous passage of time.
I figured out the solution with: First of all creating a jasmine.spyObj like this:
    const authenticationMock: AuthenticationService = jasmine.createSpyObj('AuthenticationService',
    ['usernameAnnounced']);
Assign it to the mocked service:  {provide: AuthenticationService, useValue: authenticationMock}.
And it the unit test itself just assign the property with ur expected result:
const spy = TestBed.get(AuthenticationService);
    spy.usernameAnnounced = Observable.of('dummyUser');
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With