
code-it ์ฌํ ๊ณผ์ ์์ ๋ฐฐ์ด ํ ์คํธ๋ฅผ ๋ด ํ๋ก์ ํธ์ ์ ์ฉ ์์ผ๋ณด๊ธฐ๋ก ํ๋ค!
ํต์ฌ์ด ๋๋ API ํธ์ถ์ ๊ดํ ํ ์คํธ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด์ ๋ฐฐ์ด ์ ๋ค์ ๊ธฐ๋กํ๊ธฐ๋ก ํ๋ค.
describe("getProducts", () => {
it("should fetch featured products, async () => {
// ํ
์คํธ ์ฝ๋ ์์ฑ
})
)}
describe ๋ ํ
์คํธ ์ค์ํธ๋ฅผ ์ ์ํ๊ณ , it์ ๊ฐ๋ณ ํ
์คํธ ์ผ์ด์ค๋ฅผ ๋ํ๋
๋๋ค.
beforeEach(() => {
global.fetch = jest.fn();
});
afterEach(() => {
jest.resetAllmocks();
});
beforeEach๋ ํ
์คํธ ์ ์ค๋น ์์
afterEach๋ ํ
์คํธ ํ ์ ๋ฆฌ ์์
์ด๋ค.
ํ
์คํธ ์ ์ fetch๋ฅผ ๋ชจํนํ๊ณ afterEach๋ฅผ ํตํด ๋ชจํน์ ์ด๊ธฐํํ๋ค.
์ด์ ๋ ๋ค๋ฅธ ํ ์คํธ์ ์ํฅ์ ์ฃผ์ง ์๊ธฐ ์ํด์์ด๋ค.
jest.mock("query-string", () => ({
stringifyUrl: ({ url, query }: { url: string; query: any }) => {
const urlObj = new URL(url);
Object.entries(query).forEach(([key, value]) => {
if (value !== undefined) {
urlObj.searchParams.append(key, String(value));
}
});
return urlObj.toString();
},
}));
๋๋ query-string์ ๋ชจํนํ๋ค. ์ฒ์์ ์ด๋ป๊ฒ ํ๋์ง ๋ชฐ๋ผ์ ์์ฒญ ๊ฒ์ํ๊ณ ๋์๋ค๋
๋ค..
๋ชจํน์ ํด์ผํ๋ ์ด์ ๋ ํ
์คํธ ํ๊ฒฝ์ ์ ์ดํด์ผํ๊ณ ์ธ๋ถ ์์กด์ฑ์ ์ ๊ฑฐํด์ผ ํ๊ธฐ ๋๋ฌธ์ด๋ผ๊ณ ํ๋ค.
(global.fetch as jest.Mock).mockResolvedValue({
json: () => Promise.resolve(mockProducts),
});
fetch๋ฅผ ๋ชจํนํ๋ ์ด์ ๋ ์ค์ ๋คํธ์ํฌ์ ์์ฒญ ์์ด ์๋ต ๋ฐ์ดํฐ๋ฅผ ์๋ฎฌ๋ ์ด์ ํ๊ณ ์๋ฌ ์ํฉ์ ํ ์คํธ ํ๊ธฐ ์ํจ์ด๋ค.
const STORE_ID = "ํ์ํ ํ๊ฒฝ ๋ณ์";
process.env.NEXT_PUBLIC_API_URL = `http://localhost:3000/api/${STORE_ID}`;
ํ ์คํธ ํ๊ฒฝ ๋ณ์๋ฅผ ์ค์ ํ๋ ์ด์ ๋ ํ ์คํธ ํ๊ฒฝ ๋ถ๋ฆฌ์ ์ค์ API์์ ํผ๋์ ๋ฐฉ์งํ๊ณ ํ ์คํธ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๊ธฐ ์ํจ์ด๋ค.
it("should fetch featured products", async () => {
// Given: ํ
์คํธ ์ค๋น
(global.fetch as jest.Mock).mockResolvedValue({
json: () => Promise.resolve(mockProducts),
});
// When: ํ
์คํธ ์คํ
const result = await getProducts({ isFeatured: true });
// Then: ๊ฒฐ๊ณผ ๊ฒ์ฆ
expect(result).toEqual(mockProducts);
expect(fetch).toHaveBeenCalledWith(
`http://localhost:3000/api/${STORE_ID}/products?isFeatured=true`,
expect.any(Object)
);
});
Given์ ํ
์คํธ ์ค๋น ๋จ๊ณ
When์ ํ
์คํธ ๋์ ์คํ
Then์ ๊ฒฐ๊ณผ ๊ฒ์ฆ