【发布时间】:2021-06-24 11:21:04
【问题描述】:
我有一个 react 组件,它使用 Axios 来获取 HomePage.js 和 Post.js 的数据以将其呈现在屏幕上。我正在尝试为他们两个编写测试用例。但是每次我尝试失败时,有人可以帮助我理解我在测试用例中做错了什么。谢谢
我是测试新手,我知道组件测试任何建议都将不胜感激!
主页.js
import React, { useState, useEffect } from 'react';
import Post from '../../Components/Post/Post';
import axios from 'axios';
const HomePage = () => {
const [posts, setPosts] = useState('');
const url = 'https://jsonplaceholder.typicode.com/posts/1/comments';
useEffect( () => {
AllPosts();
}, []);
const AllPosts = () => {
axios.get(`${url}`)
.then((response) => {
const allPosts = response.data;
setPosts(allPosts);
})
.catch( error => console.error(`Error: ${error}`));
}
return (
<div >
<Post className ="Posts" posts = {posts}/>
</div>
)
}
export default HomePage;
HomePage.test.js
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Post from './Post';
configure ({adapter: new Adapter()});
describe('<Post />', () => {
it('Should render all the posts ', () => {
const wrapper = shallow(<Post />);
expect (wrapper.length).toBe(1);
});
});
Post.js
import React from 'react';
import './Post.css';
const Post = (props) => {
const displayPosts = (props) => {
const { posts } = props;
if ( posts.length > 0) {
return(
posts.map( (post) => {
return(
<div className ="Post" >
<p><b>Name :</b> {post.name}</p>
<div className = "Info">
<div className = "email"> <b>Email :</b> {post.email}</div>
<div className = "body"> <b>Body :</b>{post.body}</div>
</div>
</div>
)
})
)
}
}
return (
<div className = "Posts">
{ displayPosts(props) }
</div>
)
}
export default Post;
Post.test.js
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Post from './Post';
configure ({adapter: new Adapter()});
describe('<Post />', () => {
it('Should render all the posts ', () => {
const wrapper = shallow(<Post />);
expect (wrapper.find(Email)).toHaveLength(3);
});
});
【问题讨论】:
-
shallow 忽略 useEffect 并且不应用于此目的。不等待 axios 返回的承诺。不应在单元测试中执行真正的请求。 Enzyme 在测试功能组件方面表现不佳,React 测试库做得更好。
标签: reactjs unit-testing jestjs react-hooks enzyme