ERROR
[story book/msw/error] Cannot read properties of undefined (reading 'get')
더라
2025. 5. 25. 01:40
728x90
에러 내용
react에서 story book에 msw를 연결하는 과정 중 다음의 에러를 마주했다.
Cannot read properties of undefined (reading 'get')
해결 과정
검색을 해도 적합한 자료를 찾지 못했다.
그러다가 npm run storybook
명령어 실행시 뜨는 warning를 보았다.
'export 'rest' (imported as 'rest) was not found in 'msw'...'
이는 현재 버전에서는 msw패키지의 rest가
더이상 지원되지 않는다는 안내문인듯 했다.
코드 확인
기존 코드
// src/mocks/handlers.js
import { rest } from "msw";
export const handlers = [
rest.get(경로 및 주소, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
data: {
//생략
},
})
);
}),
];
(⚠ 경로 및 주소 부분은 글 작성을 위해 '실제 경로 및 주소'를 대체한 단어다.)
기존 핸들러 코드를 보면
rest
를 import해
rest.get()
을 사용하고 있다.
작성일 기준
스토리북의 최신 버전인 8에서
rest가 더이상 지원하지 않는다고 하니
msw-storybook-addon 에서 최신 버전의 코드 예제를 확인했다.
rest대신 http를 사용하는 방식으로 변경된 듯 했다.
변경한 코드
// src/mocks/handlers.js
import { http } from "msw";
export const handlers = [
http.get(경로 및 주소, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
data: {
// 생략
},
})
);
}),
];
http
를 import한 후 http.get()
로 변경한 뒤
에러를 해결할 수 있었다.
요약
story book 8버전에서
rest로 핸들러를 작성했다면
http로 변경해보자.
// before
import { rest } from 'msw';
rest.get(...);
// after
import { http } from 'msw';
http.get(...);
728x90