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

164
Visualizações
What I am doing wrong when testing this method?

I am trying to test a method within a service that performs an http post. I have mock the service in my spec.ts and all seems correct for me, but the boolean variable that I expect true is showing false. This is the Jasmine spec list failure report:

Spec List | Failures
SkillAddService > Testing postSkillforMember() success
Expected false to be truthy.

This the method I want to test:

postSkillforMember(memberId: string, skillFormBody: any, successCallback: Function, errorCallback: Function) {
    this._http
      .post<Skill>(`${this._membersUrl}/${memberId}/skills`, skillFormBody, {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
        responseType: 'json',
        observe: 'body',
      })
      .subscribe({
        next: (value) => { 
          this.newSkill = value;
        },
        complete: () => { 
          console.log("entrando");
          successCallback(this.newSkill);

        },
        error: (error) => { catchError(this.handleError);
          errorCallback(error);
        }
    });
  }

And this is my spec.ts file. I mock the service and then call the method with dummy but correct parameters:

describe('SkillAddService', () => {

  let mockHttp: HttpClient;
  let mockSkillAddService: jasmine.SpyObj<SkillAddService>;

  beforeEach(() => {
    mockSkillAddService = jasmine.createSpyObj<SkillAddService>('SkillAddService', ['postSkillforMember']);
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [{provide: SkillAddService, useValue: mockSkillAddService}]
    });
    mockHttp = TestBed.inject(HttpClient);
   
  });

  it('should be created', () => {
    expect(mockSkillAddService).toBeTruthy();
  });

  it('Testing postSkillforMember() success', () => {

    const skillFormBody = {
      skill: {
          "id": '1',
          "skill": ""
      },
      skillLevel: {
          "id": '1',
          "skillLevel": ""
      }
    }
    let successCallback = false;
   
    mockSkillAddService.postSkillforMember('1', skillFormBody, () => {successCallback = true}, () => {})
    expect(successCallback).toBeTruthy();
  });
});

Thank you in advance, I really appreciate your help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

mockSkillAddService.postSkillforMember is an asynchronous function. It return before it calls the callback function.

Therefore successCallback is still false when you reach the expect.

Try wrapping your call to mockSkillAddService.postSkillforMember in a promise.

it('Testing postSkillforMember() success', async () => {
    ...
    const successCallback = await new Promise(resolve => mockSkillAddService.postSkillforMember('sdfsdfds', skillFormBody, () => 
    resolve(true), () => resolve(false)))
    expect(successCallback).toBeTruthy();
    ...
about 4 years ago · Juan Pablo Isaza Relatório

0

As far as I understand, you want to test the postSkillforMember of the SkillAddService. But in your test, you are mocking this method. That means, the real code will not be executed, and with that of course the variable you expect to change will not change.

You have to provide the real service:

providers: [SkillAddService]
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