3. MSW

์‹ค์Šต ๋ ˆํฌ

์ฝ”๋“œ ๋ ˆ๋ฒจ์ด ์•„๋‹ˆ๋ผ ํ”„๋ก์‹œ๋ฅผ ์ด์šฉํ•ด ๋„คํŠธ์›Œํฌ ๋ ˆ๋ฒจ์—์„œ ๊ฐ€์งœ ๊ตฌํ˜„.

์˜คํ”„๋ผ์ธ ์ž‘์—… ๋“ฑ์„ ์ง€์›ํ•˜๊ธฐ ์œ„ํ•œ ์„œ๋น„์Šค ์›Œ์ปค์˜ ๊ธฐ๋Šฅ์„ ์œ ์šฉํžˆ ํ™œ์šฉํ•œ ๊ฒƒ.

Service worker

์„œ๋น„์Šค ์›Œ์ปค๋ฅผ ํ™œ์šฉํ•ด ๋„คํŠธ์›Œํฌ ํ˜ธ์ถœ์„ ๊ฐ€๋กœ์ฑ„ Mock Response๋ฅผ ์ฃผ๋Š” ๊ฒƒ.

https://fe-developers.kakaoent.com/2022/221208-service-worker

์„ค์น˜

npm i -D msw

jest.config.js ํŒŒ์ผ์˜ 'setupFilesAfterEnv' ์†์„ฑ์— setupTests.tsํŒŒ์ผ ์ถ”๊ฐ€.

module.exports = {
 testEnvironment: 'jsdom',
 setupFilesAfterEnv: [
  '@testing-library/jest-dom/extend-expect',
  '<rootDir>/src/setupTests.ts', // ์—ฌ๊ธฐ
 ],
 transform: {
  '^.+\\.(t|j)sx?$': ['@swc/jest', {
   jsc: {
    parser: {
     syntax: 'typescript',
     jsx: true,
     decorators: true,
    },
    transform: {
     react: {
      runtime: 'automatic',
     },
    },
   },
  }],
 },
};

ํŒŒ์ผ๋„ ๋งŒ๋“ค์–ด์ค€๋‹ค.


// src/mocks/server.ts
// ๋”ฐ๋กœ eslint ์žก์•„์ค„ ์ˆ˜ ์žˆ์ง€๋งŒ ์ผ๋‹จ ์ด๋ ‡๊ฒŒ ์žก๋Š”๋‹ค.
// eslint-disable-next-line import/no-extraneous-dependencies
import { setupServer } from 'msw/node';
import handlers from './handlers';
const server = setupServer(...handlers);
export default server;



// src/mocks/handlers.ts
import { rest } from 'msw';
import fixtures from '../../fixtures';

const handlers = [
  rest.get('http://localhost:3000/restaurants', (req, res, ctx) => {
    const { products } = fixtures;
    return res(
      ctx.status(200), // ์•ˆ์จ๋„ ๊ธฐ๋ณธ์ด 200
      ctx.json({ products }),
    );
  }),
];
export default handlers;


// App.test.ts
import { render, screen, waitFor } from '@testing-library/react';
import App from './App';

// jest.mock ๋ถˆํ•„์š”.

test('App', () => {
  render(<App />);

 //๋ฐ์ดํ„ฐ ๋“ค์–ด์˜ค๊ธฐ์ „ ํ…Œ์ŠคํŠธํ•˜๋ฉด ํ†ต๊ณผ ์•ˆ๋˜๋‹ˆ, waitFor๋ฅผ ๊ฑธ์–ด์ค€๋‹ค.
  waitFor(() => {
    screen.getByText('๋ฉ”๊ฐ€๋ฐ˜์ ใ„นใ…‡ใ„ด');
    // ์•ˆ์— ์žˆ๋Š” ์ด๊ฒŒ ๋ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฐ๋‹ค. 
    // ๊ธฐ๋‹ค๋ฆฐ๋‹ค๊ธฐ๋ณด๋‹ค ๋ ๋•Œ๊นŒ์ง€ ํ™•์ธํ•œ๋‹ค๋ผ๋Š” ๊ฐœ๋…์ด๋ผํ•จ.
  });
});

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์•ˆ๋ผ์•ผ ๋˜๋Š”๋ฐ ๋ผ๋ฒ„๋ฆฐ๋‹ค.

waitFor๊ฐ€ promise๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— async await์„ ๊ฑธ์–ด์ค˜์•ผํ•˜๋Š”๋ฐ,.

์ด๋ ‡๊ฒŒ ๋ฐ”๊ฟ”์ฃผ๋ฉด ํ†ต๊ณผ ์•ˆ๋œ๋‹ค.

test('App', async () => {
  render(<App />);

  await waitFor(() => {
    screen.getByText('๋ฉ”๊ฐ€๋ฐ˜์ ');
    // ์•ˆ์— ์žˆ๋Š” ์ด๊ฒŒ ๋ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฐ๋‹ค. ๋ ๋•Œ๊นŒ์ง€ ํ™•์ธํ•œ๋‹ค๋ผ๋Š” ๊ฐœ๋…์ด๋ผํ•จ.
  });
});

์ด๋ ‡๊ฒŒ ๋ฐ”๊พธ๊ณ  '๋ฉ”๊ฐ€๋ฐ˜์ ' ๊ฐ’์„ ์ค˜๋„ ํ•ด๊ฒฐ๋˜์ง€ ์•Š๋Š”๋‹ค.

!! ReferenceError: fetch is not defined !!

fetch๊ฐ€ ๋ธŒ๋ผ์šฐ์ €์—์„  ๋˜๋Š”๋ฐ node์—์„  ์•ˆ๋œ๋‹ค

github์—์„œ ๋งŒ๋“  fetch polyfill ํ•ด์ค˜์•ผํ•œ๋‹ค.

fetch๋Š” window์— ์žˆ๋‹ค.

์„ค์น˜ํ•ด์ค€๋‹ค.

npm install whatwg-fetch --save

Polyfill์ด๋ž€

์ด์ „ ๋ธŒ๋ผ์šฐ์ €์—์„œ ๊ธฐ๋ณธ์ ์œผ๋กœ ์ง€์›ํ•˜์ง€ ์•Š๋Š” ์ตœ์‹  ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๋ฐ ํ•„์š”ํ•œ ์ฝ”๋“œ.

Last updated