在承诺中通过Jest测试,但在async / await中失败

时间:2018-06-11 10:46:22

标签: javascript async-await jestjs

我正在使用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

2 个答案:

答案 0 :(得分:0)

承诺版本实际上并不起作用。如评论中所述(thisthis),测试结果被跳过,给出了通过测试的错误感觉。将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)
})