上下文:我正在尝试使用 jest 和 supertest 为我正在编写的 MongoDB 应用程序设置测试
目的:将 postArticleByAPI 函数返回的值分配给常量 id。
问题:它返回 Promise { <pending> }
我尝试过的:
undefined
。我认为我从根本上不理解 Promise,即如何分配它们在 Promise 之外返回的值。这可能吗?有人有什么建议吗?
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);
});
});
答案 0 :(得分:0)
确实 postArticleByAPI
返回一个 Promise
并且在您登录时它没有被解析。你应该这样写:
describe('Test POST through API', () => {
test('It should response the POST method /api/articles', async () => {
const id = await postArticleByAPI(articleData);
console.log(id);
});
});
另外不要忘记从 postArticleByAPI
返回 Promise:
function postArticleByAPI(article) {
return 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;
});
}
如果你想使用async
和await
,你不应该使用.then
-
async function postArticleByAPI(article) {
const response =
await request(app)
.post('/api/articles')
.send(article)
.expect(200)
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;
}