Jest:Mock
lastmod 2026-11-10created 2022-04-113 edits
Jest:Mock은 JavaScript 테스트 프레임워크 Jest 의 모킹(mocking) 기능을 정리한 문서이다. jest.mock()으로 모듈 전체를 가짜 구현으로 바꾸거나 jest.fn()으로 호출 기록을 남기는 모의 함수를 만들 수 있고, mockResolvedValue나 mockRejectedValue로 비동기 결과를 지정한다. 외부 API 호출이나 네트워크 의존성을 제거해 테스트를 결정적으로 만드는 데 쓴다.
Example
import axios from "axios";
import { BASE_URL, fetchUsers } from "./utils";
jest.mock("axios");
describe("fetchUsers", () => {
describe("when API call is successful", () => {
it("should return users list", async () => {
// given
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Andrew" },
];
axios.get.mockResolvedValueOnce(users);
// when
const result = await fetchUsers();
// then
expect(axios.get).toHaveBeenCalledWith(`${BASE_URL}/users`);
expect(result).toEqual(users);
});
});
describe("when API call fails", () => {
it("should return empty users list", async () => {
// given
const message = "Network Error";
axios.get.mockRejectedValueOnce(new Error(message));
// when
const result = await fetchUsers();
// then
expect(axios.get).toHaveBeenCalledWith(`${BASE_URL}/users`);
expect(result).toEqual([]);
});
});
});