Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
Angular Unit test cases for promise

I am trying to write a unit test case for service inside Promise, I can able to execute promise call, but can't able to execute inside services, Also in code coverage report, it shows code is not covered for promise line. Please tell me where I am doing wrong.

The below file is our usercomponent.component.ts.

             import {Component, OnInit} from '@angular/core';
             import {UserService} from "../services/user.service";

             @Component({
                 selector: 'user',
                 templateUrl: './user.component.html',
                styleUrls: ['./user.component.css']
              })

        export class UserComponent implements OnInit {

          constructor(private userService: UserService) {}
          
          getToken(){

             return new Promise(function(resolve,reject){
                if(this.token){
                    resolve(this.token);
                 }else{
                          this.userService.getToken().subscribe((data)=>{
                            resolve(data.token); 
                         },
                        error: (error) => {
                             reject(error)
                         },
                         )
                     }
              })

             }
           }

The below file is our user.component.spec.ts file

          import {UserComponent} from './user.component';
          import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
          import {of} from 'rxjs';
          import {UserService} from "../services/user.service";
          
          class MockUserClass{
               getToken(){ return new Observable()}
           }

          describe('UserComponent', () => {
              const fixture;
              const component;

              beforeEach(
                  wairForAsync(()=>{
                      Test.Bed.configureTestingModule({
                          declarations: [UserComponent],
                          providers: [{{provide:UserService,useClass:MockUserClass}]
                       }).compileComponents();
                  });
              )

              beforeEach(()=>{
                 fixture = TestBed.createComponent(UserComponent);
                 component = fixture.componentInstance;
                 fixture.detectChanges();
              })

              it(`should call getToken method`,fakeAsync(()=>{
              const spy =  spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));
              const spyOnService = sppyOn(component.userService, 'getToken').and.returnValue(of(mockData))
              component.getToken();
              tick();
              expect(spy ).toHaveBeenCalled();
              expect(spyOnService).toHaveBeenCalled();
              }));
          });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you are making a spy:
const spy = spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));.
Then, when you call this method, it will return your fake promise. So it won't call your service, it will only return your mocked promise. So this code does not make any sense:

component.getToken();
expect(spy).toHaveBeenCalled();

The expect() statement will always be true, since you call it manually. Try removing this spy first:

          // const spy =  spyOn(component,'getToken').and.returnValue(Promise.resolve('token'));
          const spyOnService = spyOn(component.userService, 'getToken').and.returnValue(of(mockData))
          component.getToken();
          tick();
          // expect(spy ).toHaveBeenCalled();
          expect(spyOnService).toHaveBeenCalled();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!