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

225
Visualizações
How to mock Axios fetch in react testing

I am new to react testing and I just wanted to write a test for fetching API data of a react component.

Here is my component which fetches data successfully.

ListData.js

const ListData = () => {
  const [data, setData] = useState([]);
  const [searchValue, setSearchValue] = useState("");

  useEffect(() => {
    axios
      .get("https://images-api.nasa.gov/search?media_type=image")
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          console.log(err);
        }
      );
  }, []);

}

And I tried to write the test for the above code as follows

import { rest } from "msw";
import { setupServer } from "msw/node";
import ListData from "./Components/ListData";

const body = { hello: "world" };

const server = setupServer(
  rest.get(
    "https://images-api.nasa.gov/search?media_type=image",
    (_, res, ctx) => {
      return res(ctx.status(200), ctx.json(body));
    }
  )
);

describe("ListData", () => {
  beforeAll(() => server.listen());

  afterEach(() => server.resetHandlers());

  afterAll(() => server.close());
});

Bu I got error saying Your test suite must contain at least one test., What did I miss here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you are exactly missing what the error says u are missing, a test. If you add some test that error will disappear.

describe("ListData", () => {
  beforeAll(() => server.listen());

  afterEach(() => server.resetHandlers());

  afterAll(() => server.close());
  it('should do something', () => {
    expect(true).toBe(true)
  })
});

Also, I recommend you set up msw server on a jest setup file otherwise you will need to repeat this setup on every test file:

// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js'],
}
// jest.setup.js
import { server } from './mocks/server.js'
// Establish API mocking before all tests.
beforeAll(() => server.listen())
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers())
// Clean up after the tests are finished.
afterAll(() => server.close())

You can follow these docs: https://mswjs.io/docs/getting-started/integrate/node

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