gpt4 book ai didi

reactjs - ComponentDidMount() 中 Axios 请求的 Jest/Enzyme 单元测试

转载 作者:行者123 更新时间:2023-12-04 01:51:37 26 4
gpt4 key购买 nike

我正在尝试使用 Jest 和 Enzyme 对我现有的 React 应用程序执行一些单元测试。我对这些东西完全陌生,准确地说我不知道​​如何处理这样的测试场景。我知道要测试 API 请求调用我必须执行一些“模拟”,但我应该如何为此编写测试?。需要遵循哪些步骤?

以下是我要测试的代码片段。

首页.js

import React,{Component} from 'react'
import axios from 'axios';
import {Link} from 'react-router-dom';
import FacilityModal from '../Table/FacilityModal';

class Home extends Component {
state = {
cities:[],
name:''
}

componentDidMount() {
axios.get('/cities').then(res => {
this.setState({cities:res.data})
console.log("Oza" + JSON.stringify(res))
});
console.log(this.state.cities)
}

render() {
let postList = this.state.cities.map(city => {
return(
<div key = {city.id}>
<p>
<Link to = {'/'+city.id}>{city.name}</Link>
</p>
</div>
)
})
return(
<div className = 'align'>All Facilities (NCAL)
<div className="hr-sect">OR</div>
<div className = 'Modal'>
{postList}
</div>
<FacilityModal cityname = {this.props} />
</div>
)
}
}

最佳答案

import React from 'react';
import axios from 'axios';

export default class ArticleList extends React.Component {
constructor(props) {
super(props);
this.state = {
articles: []
}
}

componentDidMount() {
return axios.get('GET_ARTICLES_URL').then(response => {
this.setState({
articles: response.data
});
});
}

render() {
return (
<ul>
{this.state.articles.map(a => <li><a href={a.url}>{a.title}</a></li>)}
</ul>
)
}
}

// ---------

import React from 'react';
import { shallow } from 'enzyme';
import App from './App';

jest.mock('axios', () => {
const exampleArticles = [
{ title: 'test article', url: 'test url' }
];

return {
get: jest.fn(() => Promise.resolve(exampleArticles)),
};
});

const axios = require('axios');

it('fetch articles on #componentDidMount', () => {
const app = shallow(<App />);
app
.instance()
.componentDidMount()
.then(() => {
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledWith('articles_url');
expect(app.state()).toHaveProperty('articles', [
{ title: 'test article', url: 'test url' }
]);
done();
});
});

关于reactjs - ComponentDidMount() 中 Axios 请求的 Jest/Enzyme 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com