Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
Async await test cases failed using jest javascript testing library

I am using Jest testing Library for some simple async/await functions. But it's failing again and again as I am very new to jest. and can you please answer what expect.assertions(1) do here

    function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: 1,
        name: "test",
        age: 20,
      });
    }, 1000);
  });
}

test("test async await", async () => {
  const data = await fetchData();
  expect(data.id).toBe(1);
});

test("async await error", async () => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch("error");
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As I pointed out in the comments, the test for the "failure" case doesn't really make sense if this fetchData is the real function because it never 'rejects'. To test the failure case in Jest, you'd need to somehow trigger the Promise.reject case.

If we assume this fetchData is a wrapper on an api call or something else, we could imagine something like this.

You might have a library or module that is making api calls like:

// api.js
const api = {
  actualFetchData: () => {
    // this is the function that actually connects
    // to a data source and returns data
  },
};

module.exports = api;

And your fetchData function which you're trying to test looks like:

// fetchData.js
const api = require("./api");

function fetchData() {
  return api.actualFetchData();
}
module.exports = fetchData;

Then, assuming this structure matches what you're working on, you can mock the internals of fetchData and test both success and failure cases by mocking actualFetchData and using mockResolvedValue and mockRejectedValue.

// fetchData.test.js
const fetchData = require("./fetchData");
const api = require("./api");

jest.mock("./api");

const mockApiFetch = jest.fn();
api.actualFetchData = mockApiFetch;

describe("when the underlying fetch resolves", () => {
  beforeEach(() => {
    mockApiFetch.mockResolvedValue({
      id: 1,
      name: "test",
      age: 20,
    });
  });

  test("test async await", async () => {
    const data = await fetchData();
    expect(data.id).toBe(1);
  });
});

describe("when the underlying fetch fails", () => {
  beforeEach(() => {
    mockApiFetch.mockRejectedValue(new Error("failed to get data"));
  });

  test("async await error", async () => {
    expect(() => fetchData()).rejects.toThrow("failed to get data");
  });
});

You'll notice I didn't use the expect.assertions because it didn't seem like it added anything to the test. Instead, just used toThrow with text that matches the error.

I realize this is making some assumptions about a system that you haven't fully described in the initial question so this may not be exactly what you're trying to get at. Hopefully it's close.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda