Skip to content

Instantly share code, notes, and snippets.

@alexalannunes
Last active November 11, 2022 00:25
Show Gist options
  • Save alexalannunes/fe6979483fb6012a7dd0500d26163b60 to your computer and use it in GitHub Desktop.
Save alexalannunes/fe6979483fb6012a7dd0500d26163b60 to your computer and use it in GitHub Desktop.
mock axios with react
import { fireEvent, render, screen } from "@testing-library/react";
import axios from "axios";
import { getUser } from "./api";
import App from "./App";
jest.mock("axios");
const api = axios as jest.Mocked<typeof axios>;
// app.test.tsx
test("renders learn react link", async () => {
api.get.mockResolvedValue({ data: { login: "alexalannunes" } });
await getUser();
render(<App />);
fireEvent.click(screen.getByRole("button"));
expect(await screen.findByText("alexalannunes")).toBeInTheDocument();
});
// get-user-service.ts
import axios from "axios";
async function getUser() {
const req = await axios.get("https://api.github.com/users/alexalannunes");
return req.data;
}
export { getUser };
// package.json
const package = {
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!axios)/'",
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment