Skip to content

Commit 5f46087

Browse files
authored
[ADD] mock server worker
1 parent 72c6548 commit 5f46087

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Web/Front/MockServerWorker.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Mock Server Worker
2+
3+
## MSW란?
4+
MSW는 서비스 워커를 사용해 HTTP 요청을 가로채 모의 응답을 보내는 API 도구이다. 백엔드 개발이 안됐을 때 유용하게 사용 가능하다.
5+
6+
### 서비스 워커란?
7+
브라우저가 백그라운드에서 실행하는 스크립트를 의미한다.
8+
9+
1. 웹사이트와 별개로 동작, 웹페이지가 닫히더라도 비활성화되지 않는다.
10+
2. 웹사이트 요청을 가로챌 수 있다.
11+
3. 웹사이트와 네트워크 중간다리 역할을 할 수 있다. (proxy 서버 역할)
12+
4. 리소스를 캐싱할 수 있다.
13+
14+
## 사용하기
15+
### #1 msw 설치
16+
1. msw 설치
17+
18+
`npm install msw` / `npm install --save-D msv`
19+
20+
2. public/ folder에 service worker script 생성 (mockServiceWorker.js)
21+
22+
`npx msw init public/`
23+
24+
### #2 폴더 추가
25+
`src/mocks` 폴더 추가
26+
27+
### #3 API 동작을 정의
28+
29+
handlers.ts 파일에 API 동작을 정의할 수 있다 (rest 사용). 이 때, path는 full path를 작성해야한다.
30+
31+
```typescript
32+
import { rest } from 'msw';
33+
34+
export default [
35+
rest.get(
36+
'https://192.168.107.252:8087/infosafer_manager/api/v1/system-settings/backup',
37+
(req, res, ctx) => {
38+
return res(
39+
ctx.json([
40+
{ name: 'backup.auto.scheduling_time', val: '03:00' },
41+
{ name: 'backup.expired_period', val: '12' },
42+
{ name: 'backup.manual.data_type', val: 'ALL' },
43+
{ name: 'backup.manual.end_date', val: '2022-11-03' },
44+
{ name: 'backup.manual.scheduling_time', val: '2022-11-17 11:53:00' },
45+
{ name: 'backup.manual.start_date', val: '2022-11-03' },
46+
{ name: 'backup.manual.type', val: '0' },
47+
{ name: 'backup.max_disk_space', val: '90' },
48+
{ name: 'backup.path', val: '/home/test,/home/pnpweb/data/backup' },
49+
{ name: 'backup.type', val: '0' },
50+
])
51+
);
52+
}
53+
),
54+
];
55+
56+
```
57+
58+
### #4 worker 생성
59+
browser.ts 파일에 handlers.ts 에 선언한 handler를 worker에 setting 해준다.
60+
```typescript
61+
import { setupWorker } from 'msw';
62+
import handlers from '@/mocks/handlers';
63+
64+
export const worker = setupWorker(...handlers);
65+
```
66+
67+
68+
### #5 worker 실행
69+
70+
main.ts 에서 worker를 실행시킨다.
71+
```typescript
72+
if (process.env.NODE_ENV === 'development') {
73+
worker.start();
74+
}
75+
```
76+
77+
78+
79+
### 참고
80+
* [Mock Server Worker](https://mswjs.io/)
81+
* [Service Worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
82+
* [Vue.js test using msw](https://www.vuemastery.com/blog/mock-service-worker-api-mocking-for-vuejs-development-testing/)

0 commit comments

Comments
 (0)