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

144
Views
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 answers
Answer question

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 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!