不能从react test发送AXIOS请求



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

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

在测试期间正确调用createObject(json)函数,并且传递的json字符串也是正确的。不幸的是,AXIOS POST方法没有被调用。

当我点击&;Post object &;通过浏览器调用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;
}  
}

App.test.js

describe('Test', function(){

let id;         
it('addObject()', function () {

const response = PostClient.createObject(objectJSON);
this.id = response.id;
expect(response.status == 200);
});
});

App.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()方法返回一个承诺——你返回的是那个承诺,而不是返回你请求的结果。

我的建议是回顾承诺是如何起作用的;MDN有一篇很好的文章——也许可以复习一下一般的异步代码。

快速而肮脏的解决方案可能是将函数转换为async函数并使用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;
}

最新更新