【发布时间】:2018-06-11 10:46:21
【问题描述】:
我正在使用 Jest + supertest 在我的 RESTful API 上编写测试。
我的test.js 一开始是这样的:
const crypto = require('crypto')
const request = require('supertest')
const app = require('./app')
const genUUID = () => {
return ([1e7]+1e3+4e3+8e3+1e11).replace(/[018]/g, c =>
(c ^ crypto.randomFillSync(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
let uuid1 = genUUID()
let uuid2 = genUUID()
describe('Test /uuids', () => {
it('Get list of uuids', () => {
request(app).get('/api/uuids/').then(res =>
expect(res.statusCode).toBe(200)
)
})
})
describe('Test /uuids/:uuid', () => {
it('Get info of a not-existed product', () => {
request(app).get('/api/uuids/' + uuid1).then(res =>
expect(res.statusCode).toBe(400)
)
})
})
它可以工作并且所有测试都通过了。
但我喜欢 async/await 的风格,所以我将 Promise 切换为 async/await。
... // The previous part remains unchanged
describe('Test /uuids', () => {
it('Get list of uuids', async() => {
const res = await request(app).get('/api/uuids/')
expect(res.statusCode).toBe(200)
})
})
describe('Test /uuids/:uuid', () => {
it('Get info of a not-existed product', async () => {
const res = await request(app).get('/api/uuids/' + uuid1)
expect(res.statusCode).toBe(400)
})
})
这一次出现了错误。
console.error api/uuids.js:247
ERR!error: bind message supplies 1 parameters, but prepared statement "Get lists of UUIDs" requires 6
....
● Test /uuids/:uuid › Get info of a not-existed product
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
我是否正确编写了异步/等待?或者 Jest 中的 async/await 有什么问题吗?
附: node 版本为v8.11.2
【问题讨论】:
-
我怀疑第一个工作是否符合您的预期。如果期望没有通过测试,它自己将保持绿色,因为 jest 已经完成了测试。
-
可能会更改第一个版本,以便它返回承诺并测试它们是否有效。顺便说一句,您的异步/等待解决方案看起来不错。所以也许
supertest不是你所期望的。 -
在您的第一个版本中,
it回调永远不会返回承诺。也许这就是为什么它报告它们为通过,甚至没有查看结果。 -
也许您需要致电
.end()发送请求,因为您不使用来自超测的expect。 -
@AndreasKöberle @Bergi 你是对的。当我添加
return时,promise 不起作用,它会抛出与 async/await 相同的异常。原来是 API 代码的问题,而不是玩笑的问题
标签: javascript async-await jestjs