์ฝ๋ ๋ ๋ฒจ์ด ์๋๋ผ ํ๋ก์๋ฅผ ์ด์ฉํด ๋คํธ์ํฌ ๋ ๋ฒจ์์ ๊ฐ์ง ๊ตฌํ.
์คํ๋ผ์ธ ์์
๋ฑ์ ์ง์ํ๊ธฐ ์ํ ์๋น์ค ์์ปค์ ๊ธฐ๋ฅ์ ์ ์ฉํ ํ์ฉํ ๊ฒ.
Service worker
์๋น์ค ์์ปค๋ฅผ ํ์ฉํด ๋คํธ์ํฌ ํธ์ถ์ ๊ฐ๋ก์ฑ Mock Response๋ฅผ ์ฃผ๋ ๊ฒ.
์ค์น
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์ด๋
์ด์ ๋ธ๋ผ์ฐ์ ์์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ง์ํ์ง ์๋ ์ต์ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ ๋ฐ ํ์ํ ์ฝ๋.