首页 > 解决方案 > 无法从反应测试发送 AXIOS 请求

问题描述

我希望有人能给我以下问题的提示。我目前正在开发 REST API 的前端。我想测试我是否可以提交 POST 请求。

使用npm test命令,测试运行并显示此测试功能的绿色勾号。但是,没有发送 POST 请求,因此没有条目写入数据库。

测试过程中调用createObject(json)函数正确,传递的JSON字符串也正确。不幸的是,没有调用 AXIOS POST 方法。

当我通过浏览器单击“发布对象”时,将调用 AXIOS 方法并在数据库中创建一个对象。

PostClient.js

import axios from 'axios';

const options = {
    headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    } };

export class PostClient {

        // This function is called by the test, but the Axios command is not.
        static createObject(json) {

        const response = axios.post('http://localhost:8080/object/create/', JSON.stringify(json), options)
            .then(response => {
                console.log(response.data);
                return response;
            }).catch(function (error) {
                console.log(error);
            });
            return response;
    }  

}

应用程序.test.js

describe('Test', function(){
   
  let id;         

  it('addObject()', function () {
    
    const response = PostClient.createObject(objectJSON);
    this.id = response.id;

    expect(response.status == 200);

  });
});

应用程序.js

class App extends React.Component {
 
  render() {
    return (
      <>
        <h2>createObject</h2>
        <div className="createObject">
          <button onClick={() => PostClient.createObject(objectJSON)}>Post Object</button>
        </div>
       ...
      </>
    );
  }
}

export default App;

标签: javascriptreactjsaxios

解决方案


首先:阅读 Yevgen Gorbunkov 的评论 :)

第二:axios.post()方法返回一个 Promise - 您正在返回该承诺,而不是返回您的请求结果。

我的建议是回顾 promise 的工作原理;MDN 有一篇不错的文章——也许一般会复习异步代码。

快速而肮脏的解决方案可能是将您的函数转换为异步函数并使用 async/await:

static async createObject(json) {
    // Note: this might throw an error; try...catch is a good idea
    const response = await axios.post(url, payload, options);
    return response.data;
}

推荐阅读