我正在使用Jest和Enzyme来测试React组件,但是我发现很难测试一个简单的无状态组件,该组件由地图javascript函数的结果组成。
MovieCard.js 组件:
import React from 'react'
import PropTypes from 'prop-types'
const MovieCard = ({ resultsForSubmit }) =>
(
resultsForSubmit.map(r => (
<article className="card" key={r.imdbID}>
<a href={r.Poster}>
<picture className="thumbnail">
<img src={(r.Poster !== "N/A")? r.Poster : "src/assets/not-found.png"} alt={r.Title} />
</picture>
</a>
<div className="card-content clearfix">
<div className="review">
<h2>{r.Title}</h2>
<p>{r.Type}</p>
</div>
<div className="reviewer">
</div>
</div>
</article>
)
)
)
export default MovieCard;
MovieCard.propTypes = {
resultsForSubmit: PropTypes.array,
}
MovieCard.test.js
import React from 'react'
import { mount } from 'enzyme'
import MovieCard from './MovieCard';
describe('<MovieCard /><MovieCard />', () => {
const data = [
{ imdbId: '2', Poster: 'poster2', Title: 'title2', Type: 'type2' }
];
it('renders 2 <MovieCard /> components', () => {
mount(<MovieCard data={ data } />);
});
})
运行测试时,显示此错误:
**<MovieCard /><MovieCard /> › renders 2 <MovieCard /> components
TypeError: Cannot read property 'map' of undefined
4 | const MovieCard = ({ resultsForSubmit }) =>
5 | (
> 6 | resultsForSubmit.map(r => (
| ^
7 | <article className="card" key={r.imdbID}>
8 | <a href={r.Poster}>
9 | <picture className="thumbnail">**
目前,我只想测试组件是否已渲染,但是我愿意在其上使用其他测试功能。
答案 0 :(得分:0)
<MovieCard />
需要一个道具resultsForSubmit
,而您在测试中通过了data
。
尝试这样的方法:
MovieCard.test.js
describe('<MovieCard />', () => {
const resultsForSubmit = [
{ imdbId: '1', Poster: 'poster1', Title: 'title1', Type: 'type1' },
{ imdbId: '2', Poster: 'poster2', Title: 'title2', Type: 'type2' }
];
let movieCard;
beforeEach(() => {
movieCard = shallow(<MovieCard resultsForSubmit={resultsForSubmit} />);
});
it('renders 2 articles', () => {
expect(movieCard.find('article').length).toBe(2);
});
})