Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular testing mock subscribed property

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?

like image 855
MarcoLe Avatar asked Jul 05 '18 12:07

MarcoLe


People also ask

What is the use of SpyOn in Angular?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.

What is fakeAsync in Angular?

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.


1 Answers

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');
like image 107
MarcoLe Avatar answered Sep 25 '22 17:09

MarcoLe