【发布时间】:2021-05-16 01:59:35
【问题描述】:
上下文:我正在尝试使用 jest 和 supertest 为我正在编写的 MongoDB 应用程序设置测试
目标:将从 postArticleByAPI 函数返回的值分配给常量 id。
问题:它正在返回Promise { <pending> }
我尝试过的:
- Promise.resolve(postArticleByAPI) 会导致同样的问题。
- 链接 .then((res) => {console.log(res}) 会导致
undefined。
我认为我从根本上不理解承诺,或者即如何分配它们在承诺之外返回的值。这可能吗?有人有什么建议吗?
const articleData = {title: 'Hello123', doi: '123', journal: 'Facebook'};
/**
* Posts an article through the API
* @param {Object} article - the article objection containing dummy data
* @return {string} request - the article id stored in the database
**/
async function postArticleByAPI(article) {
await request(app)
.post('/api/articles')
.send(article)
.expect(200)
.then((response) => {
expect(response.body.title).toBe(article.title);
expect(response.body.doi).toBe(article.doi);
expect(response.body.journal).toBe(article.journal);
expect(response.body.id).toBeTruthy();
return response.body.id;
});
}
describe('Test POST through API', () => {
test('It should response the POST method /api/articles', () => {
const id = postArticleByAPI(articleData);
console.log(id);
});
});
【问题讨论】:
-
你没有在函数中返回任何东西
-
所有
async函数都返回一个承诺。他们就是这样工作的。您必须在返回的 Promise 上使用.then()或await才能知道它何时完成工作和/或从中获取已解决的值(如果您决定从async函数返回一个值。跨度> -
@Phix 是正确的,你忘了
return。但是return await...是一种反模式,您可以简单地编写return ...,因为所有async函数都会自动返回promise。对于这个函数,由于没有await,你也可以删除async关键字,function postArticleByAPI(article) { return request(...) }的工作原理完全相同。
标签: javascript node.js promise es6-promise