Home > Back-end >  Jest async function always returns undefined, never resolves
Jest async function always returns undefined, never resolves

Time:12-08

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?

CodePudding user response:

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']));
});
  • Related