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

172
Views
Jest: trouble with async assertion and whether a function was called

I am trying to assert that a function is called. Unfortunately it is passing unexpectedly - actually all assertions are. I believe that tests are finishing before everything is resolved.

.js code

export function callapi(input, setOptions, setSuggestStatus) {
  if (input !== '') {
    axios
      .post(
        requestURl,
        {
          input: `${input}`,
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        },
        {
          credentials: 'include',
          headers: {
            'X-CSRF-Token': document && document.getElementsByTagName('body')[0].dataset.token,
          },
        },
      )
      .then(response => {
        if (response.data.status === 'OK') {
          const optionslist = response.data.suggestions.map(item => {
            return { key: item.id};
          });
          // I need to assert that this function was called with options list
          setOptions(optionslist);
        }
      })
      .catch(e => {
        console.log(e);
      })
  }
}

test code

import axios from 'axios';
describe('callapi tests', () => {
    it('should call setOptions with options when callapi is called', () => {
      const updateFetchedData = jest.fn();
      const response = {
        data: {
          status: 'OK',
          suggestions: [{"id":1},{"id":2}]
        }
      }
      const setOptions = jest.fn();
      const expectedOptionsList = [
        {
          key: 1,
        },
        {
          key: 2,
        }
      ];
      axios.post = jest.fn(() => {
        return new Promise((resolve) => {
          resolve(response);
          // this should pass
          expect(setOptions).toHaveBeenCalledWith(expectedOptionsList)
          // this shouldn't pass but is
          expect(1).toBe(2);
        })
      })
      const setSuggestStatus = jest.fn();
      callGoogleAutoCompleteSearch('input', setOptions, setSuggestStatus);
    });
});

Right now all tests pass - obviously expect(1).toBe(2); should not pass. So all tests are passing even if they shouldn't. I think this is an async issue. Any help appreciated.

about 4 years ago · Juan Pablo Isaza
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!