【问题标题】:Testing a React Hooks component with Jest / Enzyme & Axios使用 Jest / Enzyme 和 Axios 测试 React Hooks 组件
【发布时间】: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


【解决方案1】:

我尝试使用 mount 并模拟 get 方法无法按预期工作以获得 100% 的覆盖率,

export default function HomePage (){}

it('axios mock', async () => {
    let wrapper;
    
    axios.get = jest.fn()
    jest.mock('Axios');

    const data = [
        {
          "userId": 1,
          "id": 1,
          "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        }
      ]
    
      await act(async ()=> {
        await axios.get.mockImplementationOnce(()=> Promise.resolve(data))
        wrapper = mount(<HomePage />)
      })
    
    await expect(axios.get).toHaveBeenCalledTimes(1);
    wrapper.update();
    await expect(axios.get).toHaveBeenCalledWith('https://jsonplaceholder.typicode.com/posts?_limit=5')
    await expect(wrapper.find("Post").at(0)).toHaveLength(1)
    expect(toJson(wrapper)).toMatchSnapshot();
  
  })

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2017-02-12
    • 2021-09-16
    • 2021-07-29
    • 2017-04-13
    • 1970-01-01
    • 2021-04-14
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多