Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda