MSW

์˜คํ”„๋ผ์ธ ํ™˜๊ฒฝ์ด๋‚˜ ์•„์ง ๋ฐฑ์—”๋“œ API๊ฐ€ ์—†์„ ๋•Œ, ์‹ค์ œ ๋ฐฑ์—”๋“œ API๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ํ…Œ์ŠคํŠธ ํ•  ์ˆ˜ ์žˆ๋Š” ์„œ๋น„์Šค ์›Œ์ปค์˜ ๊ธฐ๋Šฅ์„ ํ™œ์šฉ.

MSW ์„ค์น˜

npm i -D msw

Setting

๊ฐ€์งœ API ์š”์ฒญ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ handler ์ฝ”๋“œ๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค. rest api๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ 'rest'๋ฅผ import ํ•œ๋‹ค.

import { rest } from 'msw'

const BASE_URI = 'http://localhost:3000'

const handlers = [
    rest.get(`${BASE_URI}/products`, (req, res, ctx) => {
        const { products } = fixtures

        return res(
            ctx.status(200),
            ctx.json({products})
        )
    })
]

export default handlers

setupWorker() ํ•จ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ์™€์„œ ์„œ๋น„์Šค ์›Œ์ปค๋ฅผ ์ƒ์„ฑํ•ด ์ฃผ๊ณ  ๋งŒ๋“  handlers๋ฅผ ์ธ์ž๋กœ ๋„˜๊ธด๋‹ค.

// src/mocks/server.ts
import { setupServer } from 'msw/node'
import handlers from './handlers'

const server = setupServer(...handlers)

jest์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค์ •ํ•ด์ฃผ๊ธฐ

// src/setupTests.ts
import server from './mocks/server'

// jest ์‚ดํ–‰ํ•˜๋ฉด ๋ฐ”๋กœ ์‹คํ–‰
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))

// ์‹คํ–‰๋  ๋•Œ ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”
afterEach(() => server.resetHandlers())

// jest ๋๋‚  ๋•Œ
afterAll(() => server.close())

Last updated