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

132
Views
Jest async function always returns undefined, never resolves

I'm using axios to fetch some user data from an API and push them into an array in a vanilla JS file like so:

export async function fetchUsernames() {
  let usernames = [];
  axios.get("https://jsonplaceholder.typicode.com/users").then((users) => {
    for (let user of users.data) {
      usernames.push(user["username"]);
    }
    return usernames;
  });
}

The problem is, even though it works correctly on my frontend when I hook it up with react, my jest test block always gets undefined as the return value, even though I use async/await. This is my test block:

test('Usernames get fetched properly', async () => {
  const usernames = await fetchUsernames();
  expect(usernames).toBe(expect.arrayContaining(['Brett']));
});

This is the error message that I get:

 × Usernames get fetched properly (17 ms)

  ● Usernames get fetched properly

    expect(received).toBe(expected) // Object.is equality

    Expected: ArrayContaining ["Brett"]
    Received: undefined

      12 | test('Usernames get fetched properly', async () => {
      13 |   const usernames = await fetchUsernames();
    > 14 |   expect(usernames).toBe(expect.arrayContaining(['Brett']));
         |                     ^
      15 | });

      at Object.<anonymous> (src/App.test.js:14:21)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        4.038 s
Ran all test suites related to changed files.

What could most likely be the cause behind this issue?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Change fetchUser function as follows.

async function fetchUsernames() {
  let usernames = [];
  let users = await axios.get("https://jsonplaceholder.typicode.com/users");
  for (let user of users.data) {
    usernames.push(user["username"]);
  }
  return usernames;
}

This will return array of usernames.

test('Usernames get fetched properly', async () => {
  const usernames = await fetchUsernames();
  expect(usernames).toBe(expect.arrayContaining(['Brett']));
});
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!