Home > front end >  How to unit test post subscribe using karma/angular/jasmine
How to unit test post subscribe using karma/angular/jasmine

Time:11-23

How to write test case for this above block ?

And I tried to write like this :

It caught passed in local while running "ng test" but it doesn’t passed by code coverage.

Using

Angular CLI - 14.0.0

Node Version - v14.20.1

npm version - 6.14.17

this.apiService.post('/login', datavalue).subscribe({
      next: (user: any) => {
        if (user.sc === true) {
          localStorage.setItem('firstName', user.result.first_name);
          localStorage.setItem('lastName', user.result.last_name);
          localStorage.setItem('token', user.result.token);
          this.loading = false;
          this.toastr.success('Login successful');
          this.router.navigate(['/under-construction']);
          this.isSubmitted = false;
          this.loginForm.reset();
        }
        if (user.sc === false) {
          this.loading = false;
          this.toastr.error(user.error.msg);
          this.isSubmitted = false;
        }
      },
      error: (err) => {
        this.loading = false;
        this.toastr.error(err.error.error.msg);
      },
    });


it('should submit Login Form', (() => {
    myService = TestBed.inject(ApiServicesService);
    mySpy =  spyOn(myService,'post').and.returnValue(of(expectedDatas));
    component.onSubmit();
    expect(component.loading).toBeFalsy();
    expect(localStorage.getItem('firstName')).toBe(expectedDatas.result.first_name);
    expect(localStorage.getItem('lastName')).toBe(expectedDatas.result.last_name);
    expect(localStorage.getItem('token')).toBe(expectedDatas.result.token);
    expect(component.loading).toBeFalsy();
    expect(component.loading).toBe(false);
    expect(routerSpy.navigate).toHaveBeenCalledWith(['/under-construction']);
    expect(toastrService.success).toHaveBeenCalledWith('Login successful');
    fixture.detectChanges();
    expect(myService).toBeDefined();
    expect(mySpy).toBeDefined();
    expect(mySpy).toHaveBeenCalled(); 
    expect(mySpy).toBeTruthy();
  }));

CodePudding user response:

It doesn't have line coverage because this line stubs the details of the method and just returns a value:

mySpy =  spyOn(myService,'post').and.returnValue(of(expectedDatas));

To get line coverage for the post, I would test the service separately and use HttpClientTestingModule.

Check this out for more details: https://testing-angular.com/testing-services/#testing-a-service-that-sends-http-requests.

  • Related