简体   繁体   中英

Angular: unit test varibles in subscribe

I have a function that is setting a couple of values in subscribe:

private getAllStatuses(): void {
   this.refControllerService.getAllStatus().subscribe(data => {
      this.StatusDTOList = data;
      this.canEditDate = this.isEditableStatus();
      this.isDEDUser = this.userAuthorisationService.isDEDUser();
      this.initialised = true;
   });
}

canEditDate & isDEDUser are both private, they are accessed in another function:

public canEdit(): boolean {
   return this.isDEDUser && this.canEditDate;
}

I'm trying to set these two values in my test, but not having any look so far:

it('StatusComponent canEdit should return false', () => {
    spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
    spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)
    component.ngOnInit();
    expect(component.canEdit).toBeFalsy();
});

I've tried a few different approaches, and I've searched for similar questions, I'm relatively new to angular, could someone explain is what I'm attempting possible? Can I set the values within that subscribe in a test, so that I can flip the values on and off for canEdit() ?

There are quite a lot of unclear things in the question. I would be brave to try answering it.

Considering CanEdit is public and is the function under test we need to execute the function to test it's result. Changing expect(component.canEdit) to expect(component.canEdit()) .

we do not see how is the getAllStatuses executed. I would use it is called inside the ngOnInit . This function does some execution in an asynchronous way using the subscription to an Observable. That means we need to wait for that execution. Usually (not always though) await fixture.whenStable() is enough to wait for the execution of the async stuff. I suppose this test would archive the desired results:

it('StatusComponent canEdit should return false', async () => {
    spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
    spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)

    component.ngOnInit();
    await fixture.whenStable();

    expect(component.canEdit()).toBeFalsy();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM