reactjs - ReactJS Jest 酶单元测试 axios.get() axios.post()
问题描述
我的代码就像
constructor(props) {
super();
this.state = {
isLoading: true,
questionsData: [],
studyCategoryList: [],
studyList: [],
filteredStudyList: [],
selectedStudyCategory: "0",
selectedStudy: "0",
filterData: [],
deleteQuestionIndex: 0
};
}
在构造函数中,我正在初始化状态,并且我已经为下拉数据编写了以下方法
componentDidMount() {
this._isMounted = true;
axios
.get(url + "getAllQuestionsDropdownValues")
.then((response) => {
this.setState({ studyCategoryList: response.data[0],studyList: response.data[1] });
// this.setState({ studyList: response.data[1] });
// this.setState({ isLoading: false });
})
.catch((error) => {
console.log(error);
// this.setState({ isLoading: false });
});
this.getQuestionsData(this.state.selectedStudyCategory, this.state.selectedStudy);
const selectAll = "0";
this.state.selectedStudyCategory = selectAll;
this.state.selectedStudy = selectAll;
}
基于下拉选择,发布下拉选择的数据并从数据库中获取过滤后的数据。找到下面的发布方法。
getQuestionsData = (scid, sid) => {
this.setState({ isLoading: true });
axios.post(`${url}getQuestionList`, { studycategoryid: scid, studyid: sid })
.then((response) => {
this.setState({ questionsData: response.data, filterData: response.data });
})
.catch((error) => {
this.setState({ isLoading: false });
});
}
使用 axios 编写 uint 测试用例时,我无法在 axios get 和 post 方法上使用 jest 酶编写测试用例。
请提供完整的例子来实现它。
提前致谢
解决方案
为了测试 axios 请求,您需要使用jest-mock-axios
library。
> npm i --save-dev jest-mock-axios
文档清楚地说明了要遵循的步骤,这些步骤(部分)复制在这里:
接下来,您需要为 Axios 设置手动 Jest 模拟:
__mocks__
在项目根目录中创建目录- 在这个新目录中创建一个名为
axios.js
- 将以下代码段复制并粘贴到
axios.js
文件中
// ./__mocks__/axios.js
import mockAxios from 'jest-mock-axios';
export default mockAxios;
然后,这是一个基本的测试文件示例来测试您的axios.post
请求:
import mockAxios from 'jest-mock-axios';
import { mount } from 'enzyme';
import YourComponent from '../src/YourComponent';
afterEach(() => {
// cleaning up the mess left behind the previous test
mockAxios.reset();
});
it('YourComponent should get data', () => {
mockAxios.mockResponse({ data : <your_mocked_data> });
// using the component, which should make a server response
let clientMessage = 'client is saying hello!';
mount(<YourComponent>);
// since `get` method is a spy, we can check if the server request was correct
// a) the correct method was used (get)
// b) went to the correct web service URL ('/<your_service_url>/')
// c) if the payload was correct (<your_mocked_data>)
expect(mockAxios.get).toHaveBeenCalledWith('/<your_service_url>/', {data: <your_mocked_data> });
});
测试post
应该看起来一样。
查看文档以获取更多详细信息!
推荐阅读
- swift - 无法将类型 () 的返回表达式转换为返回类型 WebImage?
- python - 预期 TensorFlow 计算,发现内在
- javascript - NGRX 选择器更新太频繁
- python - Tkinter 输出显示在 Tkinter 窗口之外
- dns - 使用 Puppeteer 保护 DNS
- python - 使用python针对文件目录自动执行一系列文件比较功能
- hadoop - 使用 Kafka Connect 文件系统连接器使用远程文件
- c++ - 从可调用类型中提取签名
- javascript - JS同步循环没有停止
- linux - Bash Shell 脚本 - 降低管道难度