问题描述
我想更改以下异步/等待代码
const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')
const api = supertest(app)
test("total number of blogs",async () => {
const response = await api.get('/api/blogs')
expect(response.body).toHaveLength(1)
})
afterall(() => {
mongoose.connection.close()
})
这样的承诺:
const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')
const api = supertest(app)
test("total number of blogs",() => {
api.get('/api/blogs')
.then( response => {
expect(response.body).toHaveLength(1)
})
})
afterall(() => {
mongoose.connection.close()
})
解决方法
为了澄清@jonrsharpe 的评论,您应该从测试函数中返回承诺:
test("total number of blogs",() => {
return api.get('/api/blogs')
.then( response => {
expect(response.body).toHaveLength(1)
})
})
,
在第一个版本中,您在测试中返回一个 Promise。测试库收到此承诺并等待它完成,然后才会将测试视为“已完成”。
所以你要做的是:
test("total number of blogs",() => {
return api.get('/api/blogs')
.then( response => {
expect(response.body).toHaveLength(1)
})
})
不要忘记第一个例子已经可以使用 promises(async/await 只是 promises)
编辑是因为我查看了文档:p