useEffect(() => {
async (orderType) => {
try {
let response = await axios.get(`http://localhost:5001/${orderType}`);
setItems(response.data);
} catch (error) {
setError(true);
}
};
}, [orderType]);
// 에러 났으면
if (error) return <ErrorBanner message="에러가 발생했습니다." />;
return (
<>
<p>총 가격: {orderDatas.totals[orderType]}</p>
<div>
{items.map((item) => (
<ItemComponents
key={item.name}
name={item.name}
imagePath={item.imagePath}
/>
))}
</div>
</>
);
이때 테스트를 하기 위해서는 서버의 데이터를 불러올 수 없기 때문에 가짜 데이터를 이용해야 한다.
react 내에서 요청을 보낼 때,
msw 다운로드
npm install msw --save
handler를 array 형태로 원하는 api 요청과, 결과를 적어준다.
src/mocks/handlers.js
import { rest } from "msw";
export const handlers = [
rest.get("http://localhost:5001/products", (req, res, ctx) => {
return res(
ctx.json([
{
name: "America",
imagePath: "/images/america.jpeg",
},
{
name: "England",
imagePath: "/images/england.jpeg",
},
])
);
}),
rest.get("http://localhost:5001/options", (req, res, ctx) => {
return res(
ctx.json([
{
name: "Insurance",
},
{
name: "Dinner",
},
])
);
}),
rest.post("http://localhost:5001/order", (req, res, ctx) => {
let dummyData = [{ orderNumber: 2131234324, price: 2000 }];
return res(ctx.json(dummyData));
}),
];
만들어준 핸들러를 서버로 등록해야 사용가능하다.
mocks/server.js
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
// mocking server 생성
export const server = setupServer(...handlers);
만들어준 서버를 테스트에서 사용하기 위해서 root에서 등록해준다.
Root는 setupTests.js 이다
import "@testing-library/jest-dom";
import { server } from "./mocks/server";
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
실제로 되는지 테스트를 해보도록 한다.
이미지 불러오는지 확인
더미 이미지가 두개이므로 두개를 확인한다.
test("displays product images from server", async () => {
render(<Type orderType="products" />);
const productImages = await screen.findAllByRole("img", {
name: /product$/i,
});
expect(productImages).toHaveLength(2);
const altText = productImages.map((element) => element.alt);
expect(altText).toEqual(["America product", "England product"]);
});
/product$/i
$
: 이 요소로 끝나는 것은 다 가져온다./i
: 대소문자 안가리고 찾는다.체크박스 가져오기
옵션의 갯수가 두개인지 확인한다 (더미 2개)
test("fetch option information from server", async () => {
render(<Type orderType="options" />);
const optionCheckboxes = await screen.findAllByRole("checkbox");
expect(optionCheckboxes).toHaveLength(2);
});
server.resetHandlers
server의 핸들러를 변경하여 더미 데이터가 아닌 에러가 왔을 때,
에러창이 뜨는지 확인
test("when fetching product datas, face an error", async () => {
server.resetHandlers(
rest.get("http://localhost:5001/products", (req, res, ctx) => {
return res(ctx.status(500));
})
);
render(<Type orderType="products" />);
const errorBanner = await screen.findByTestId("error-banner");
expect(errorBanner).toHaveTextContent("에러가 발생했습니다.");
});