我正在使用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的风格,所以我将承诺转换为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.
我是否正确编写了async / await?或者在Jest中有关于async / await的问题吗?
P.S。 node
版本为v8.11.2
答案 0 :(得分:0)
承诺版本实际上并不起作用。如评论中所述(this和this),测试结果被跳过,给出了通过测试的错误感觉。将return
添加到promise将导致与async / await case相同的错误。
使用
模拟应用代码const app = new (require('express'))()
app.get('/api/uuids', (req, res) => {
res.status(200).end()
})
app.get('/api/uuids/:uuid', (req, res) => {
res.status(200).end()
})
module.exports = app
async / await可以告诉GET /api/uuids/:uuid
中存在错误,而承诺仍然会报告所有测试都已通过。所以async / await是正确的。
经过一些调试后,事实证明它实际上是我的代码查询数据库的问题,所以首先抛出了postgres错误。
答案 1 :(得分:0)
尝试增加超时限制(通过将以毫秒为单位的数字作为第二个参数传递给it
函数):
describe('Test /uuids', () => {
it('Get list of uuids', async() => {
const res = await request(app).get('/api/uuids/')
expect(res.statusCode).toBe(200)
}, 30000)
})
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)
}, 30000)
})