【发布时间】:2023-03-19 07:48:01
【问题描述】:
我正在尝试了解单元测试的工作原理,并构建了一个小型 React 应用程序来呈现口袋妖怪列表。 我要做的是编写一个单元测试来检查列表是否正确呈现。但是,生成的快照显示它仅呈现“正在加载...”文本,这是它在等待 API 响应时应该执行的操作。 我做错了什么?
PokemonList.test.js
import React from 'react';
import PokemonList from '../components/PokemonList';
import renderer from 'react-test-renderer';
describe('PokemonList component renders a list of Pokemon', () => {
it('renders correctly', () => {
const fetched = true;
const loading = true;
const species = [{
"0": {"name": "bulbasaur"},
"1": {"name": "ivysaur"},
"2": {"name": "venusaur"}
}];
const rendered = renderer.create(
<PokemonList fetched={fetched} loading={loading} species={species} />
);
expect(rendered.toJSON()).toMatchSnapshot();
});
});
PokemonList.js
// The PokemonList component show nothing when it mounts for the first time.
// But right before it mounts to the DOM, it makes an API call to fetch the
// first 151 Pokemon for the API and then displays them using the Pokemon component.
import React from 'react';
import Pokemon from './Pokemon';
class PokemonList extends React.Component {
constructor(props) {
super(props);
this.state = {
species: [],
fetched: false,
loading: false,
};
}
componentWillMount() {
this.setState({
loading: true
});
fetch('http://pokeapi.co/api/v2/pokemon?limit=151').then(res=>res.json())
.then(response=>{
this.setState({
species: response.results,
loading: true,
fetched: true
});
});
}
render() {
const {fetched, loading, species} = this.state;
let content ;
if (fetched) {
content = <div className="pokemon--species--list">{species.map((pokemon, index) => <Pokemon key={pokemon.name} id={index+1} pokemon={pokemon} />)}</div>
} else if (loading && !fetched) {
content = <p className="loading"> Loading ...</p>
} else {
content = <div/>
}
return (
<div>
{content}
</div>
)
}
}
export default PokemonList;
PokemonList.test.js.snap
exports[`PokemonList component renders a list of Pokemon renders correctly 1`] = `
<div>
<p
className="loading">
Loading ...
</p>
</div>
`;
【问题讨论】:
-
loading和fetched不应同时为真。正在获取数据loading或fetched -
@dcodesmith 我尝试更改这些值,但在快照中仍然得到相同的输出
-
成功获取数据后,您的
loading状态应为false而不是true,因为您已完成数据获取。修复它,看看会发生什么 -
@dcodesmith 我现在已经解决了这个问题,应用程序仍然按预期工作,但测试仍然在快照中输出“正在加载...”:(
-
检查下面的答案。希望对您有所帮助。
标签: javascript unit-testing reactjs jestjs snapshot