Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda