나는 상당히 새로운 반응하는 테스트-라이브러리와 일반적으로 테스트합니다. 고 싶 테스트 구성 요소를 가져오는 데이터에서는 API 를 useEffect 후크. 그 후에 저장하는 로컬 상태입니다. 렌더링 이러한 배열과 데이터 배열입니다.지도 있지만,나 Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'map')]
오류가 있습니다. 나는 가능하게 하는 잘못된 내에서 테스트,나는 연구를 많이하지만 해결할 수 없었습니다.
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom'
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { OnePiece } from '.';
const server = setupServer(rest.get('server http address', (req, res, ctx) => {
const totalData = [
{ name: "doffy", price: 100, image: "image url" },
{ name: "lamingo", price: 500, image: "image url" }
];
return res(
ctx.status(200),
ctx.json({
data: { crew: totalData }
})
)
}))
beforeAll(() => server.listen());
afterAll(() => server.close());
beforeEach(() => server.restoreHandlers());
//console.log("mocking axios", axios)
describe('OnePiece', () => {
test('fetches the data from the API and correctly renders it', async () => {
//Here's probably where i fail. Please someone tell me the right way :)
await render(<OnePiece />)
const items = await screen.findAllByAltText('product-image');
expect(items).toHaveLength(2);
// screen.debug()
})
})
그리고 아래는 부분의 코드 useEffect 및 totalData.지도에서 구성 요소:
const [totalData, setTotalData] = useState([]);
const [crew, setCrew] = useState('straw-hat-pirates');
useEffect(() => {
let isApiSubscribed = true;
const getOpData = async () => {
const getCrews = await axios.get('http address');
if (isApiSubscribed) {
let data = getCrews.data;
data = data[crew];
// console.log("data", data);
setTotalData(data);
}
}
getOpData();
return () => {
isApiSubscribed=false;
}
}, [crew])
.........
//in the return part
<ProductsWrapper>
{totalData.map((product, index) =>
<ProductCard key={index} name={product.name} price={product.price} imageUrl={product.image} />
)}
</ProductsWrapper>