Last active
November 11, 2022 00:25
-
-
Save alexalannunes/fe6979483fb6012a7dd0500d26163b60 to your computer and use it in GitHub Desktop.
mock axios with react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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