MSW(Mock Service Worker)
키워드
- Service worker
- MSW(Mock Service Worker)
- polyfill(폴리필)Service Worker
서비스 워커의 위치

서비스 워커의 라이프 사이클

MSW 패키지 설치
Polyfill
Last updated
키워드
- Service worker
- MSW(Mock Service Worker)
- polyfill(폴리필)

Last updated
npm i -D msw@1.3.2 -Dmodule.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',
},
},
},
}],
},
};import 'whatwg-fetch'
// fetch is not defined를 해결하기 위한 의존성 도구import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);import { setupWorker } from 'msw';
import { handlers } from './handlers';
export const worker = setupWorker(...handlers);import { rest } from 'msw';
const BASE_URL = 'http://localhost:3000';
export const handlers = [
rest.get(`${BASE_URL}/products`, (req, res, ctx) => {
const products = [
{
category: 'Fruits', price: '$1', stocked: true, name: 'Apple',
},
];
return res(
ctx.json({ products }),
);
}),
];
export default handlers;import { render, screen, waitFor } from '@testing-library/react';
import App from './App';
// jest.mock 불필요.
test('App', async () => {
render(<App />);
await waitFor(() => {
screen.getByText('Apple');
});
});
// useFectProduct를 통해 jest를 실행시, error가 발생된다.
// fetch is not defined
export default function useFetchProducts() {
const url = 'http://localhost:3000/products';
const { data, error } = useFetch<ProductResult>(url);
console.log(error)
if (!data) {
return []
}
return data.products;
}
// 호스트를 상수로 선언하여 관리한다.
const BASE_URL = process.env.API_BASE_RUL || 'http://localhost:3000'