javascript - 无法从反应测试发送 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;
解决方案
首先:阅读 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;
}
推荐阅读
- amazon-web-services - 私有子网的 EMR 安全组的 Cloud Formation
- node.js - 如何在父目录中运行构建,在部署到heroku之前将构建复制到当前目录
- c - C中数组的指针类型不兼容
- javascript - 在 this.setState 之后对象似乎未定义
- mongodb - 如何使用mongodb在数组中投影字段
- go - 使用 goroutine 处理退避
- ios - ios通用重定向链接不适用于真实设备,但适用于模拟器
- javascript - 单选按钮文本区域和 Javascript
- r - 在我的闪亮中插入 bs_embed_popover 函数
- discord.js - 如何确定发送消息的时间