首页 > 解决方案 > 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 酶编写测试用例。

请提供完整的例子来实现它。

提前致谢

标签: reactjsunit-testingjestjsenzyme

解决方案


为了测试 axios 请求,您需要使用jest-mock-axioslibrary

> 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应该看起来一样。

查看文档以获取更多详细信息!


推荐阅读