Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda