Skip to content

Instantly share code, notes, and snippets.

@alvarogfn
Last active March 20, 2025 14:42
Show Gist options
  • Save alvarogfn/2812880da2aae62666d0c771d5344f13 to your computer and use it in GitHub Desktop.
Save alvarogfn/2812880da2aae62666d0c771d5344f13 to your computer and use it in GitHub Desktop.
Evitando usar waitFor ou findBy para melhorar a performance dos testes com mocks.
// App.test.tsx
import { describe, it } from "vitest";
import { render, screen } from "@testing-library/react";
import { App } from "./App";
// Comente ou descomente essa linha para ver a diferença entre mockado e não mockado.
// vi.mock(import("./useFetch"));
describe((""), () => {
it("Sem mockar a chamada a API", async () => {
render(<App/>);
// findBy vai chamar waitFor por debaixo dos panos e o teste será lento.
await screen.findByText("Oi, eu não estou mockado!");
screen.debug();
})
it("Mockando a chamada a API", () => {
render(<App/>);
// Teste rápido, com hook mockado os dados aparecem na montagem
screen.getByText("Oi, eu estou mockado!");
screen.debug();
})
})
// App.tsx
import { useFetch } from "./useFetch";
export const App = () => {
const data = useFetch();
return <div>{data}</div>
}
// __mocks__/useFetch.ts
import {useState} from "react";
export function useFetch() {
const [data] = useState<string>('Oi, eu estou mockado!');
return data;
}
// useFetch
import {useEffect, useState} from "react";
const fetchSomeData = () => {
return new Promise<string>((resolves ) => {
setTimeout(() => {
resolves('Oi, eu não estou mockado!');
}, 200);
})
}
export function useFetch() {
const [data, setData] = useState<string>();
useEffect(() => {
async function fetchData() {
const response = await fetchSomeData();
setData(response)
}
fetchData();
}, [setData]);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment