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

158
Visualizações
Jasmine: Testing that a method passed in as an argument to another method gets run

My code is as follows

//agency_controller.js
import axios from 'axios';

export const getProducerNamesAndBillingPlan = ({ agencyId = '', onSuccess= (x) => x } = {} )  => {
  if(!!agencyId) {
    axios.get('/agency/' + agencyId)
         .then(response => onSuccess.call(this, response['data']))
         .catch(error => console.error(error))
  }
}
//agency_controller.spec.js
import { getProducerNamesAndBillingPlan } from "../../../../app/javascript/packs/controllers/agencies_controller";
import axios from 'axios';

const mockAxiosPromise = (response) => {
  return new Promise((resolve, _reject) => {
    resolve({ status: 200, data: response});
  });
}

describe('#getProducerNamesAndBillingPlan', () => {
...
it('calls the given onSuccess method if the request is successful', () => {
    spyOn(axios, 'get').and.callFake(() => {
      return mockAxiosPromise('foo')
    })

    const mockMethod = (x) => console.log(x)

    spyOn(console.log, 'call')

    getProducerNamesAndBillingPlan({ agencyId: 1, onSuccess: mockMethod })

    expect(console.log.call).toHaveBeenCalledWith('foo')
  })
})

I can tell that the code is working because when I run the test, 'foo' gets logged to the console. However the test still fails:

#getProducerNamesAndBillingPlan calls the given onSucess method if the request is sucessful FAILED
        Expected spy call to have been called with [ 'foo' ] but it was never called.
            at UserContext.<anonymous> (spec/javascripts/packs/controllers/agencies_controller.spec.js:1:17348)

Same happens with expect(console.log).toHaveBeenCalledWith('foo'). Am I doing something wrong?

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

0

The axios.get() method returns a promise, but the getProducerNamesAndBillingPlan function does not return it. You call it in the test case. When the code executes the expect statement, the promise is not resolved or rejected, so your onSuccess method was not called before the assertion.

Use async/await in test case to make sure the promise is resolved or rejected before the assertion.

agency_controller.js:

import axios from 'axios';

export const getProducerNamesAndBillingPlan = ({ agencyId = '', onSuccess = (x) => x } = {}) => {
  if (!!agencyId) {
    return axios
      .get('/agency/' + agencyId)
      .then((response) => onSuccess.call(this, response['data']))
      .catch((error) => console.error(error));
  }
};

agency_controller.spec.js:

import axios from 'axios';
import { getProducerNamesAndBillingPlan } from './agency_controller';

describe('#getProducerNamesAndBillingPlan', () => {
  it('calls the given onSuccess method if the request is successful', async () => {
    spyOn(axios, 'get').and.resolveTo({ status: 200, data: 'foo' });
    const mockMethod = (x) => console.log(x);
    spyOn(console, 'log');
    await getProducerNamesAndBillingPlan({ agencyId: 1, onSuccess: mockMethod });
    expect(console.log).toHaveBeenCalledWith('foo');
  });
});

Test result:

Executing 1 defined specs...
Running in random order... (seed: 00239)

Test Suites & Specs:

1. #getProducerNamesAndBillingPlan
   ✔ calls the given onSuccess method if the request is successful (5ms)

>> Done!


Summary:

👊  Passed
Suites:  1 of 1
Specs:   1 of 1
Expects: 1 (0 failures)
Finished in 0.01 seconds
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