Angular testing mock subscribed property

MarcoLe picture MarcoLe · Jul 5, 2018 · Viewed 8.3k times · Source

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?

Answer

MarcoLe picture MarcoLe · Jul 5, 2018

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');