我从Jest开始测试我们的API。但是,当我添加第二个测试的那一刻,一切都因超时异常而分崩离析。
这是我的代码:
const server = require('../server')
const request = require('supertest')
const path = require("path")
const fs = require("fs")
const config = require('../knexfile.js')
const knex = require('knex')(config.development)
beforeAll(async () => {
let file = fs.readFileSync(path.join(__dirname, '..', 'galaxycard.sql'), 'utf8')
await knex.raw(file)
await knex.migrate.latest()
})
afterAll(async () => {
await knex.raw(`
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO public;
`)
server.close()
})
describe("test 1", () => {
it("should not be able to add a payment for user without credit", async () => {
let response = await request(server)
.post('/v1/hampers')
.set('Content-Type', 'application/json')
.send({
entity_type: 'utility',
latitude: 1,
longitude: 1,
comment: null,
user_id: new Date().getTime(),
amount: -200,
entity_id: 1,
processed: false
})
expect(response.status).toEqual(402)
})
})
describe("test 2", () => {
let userId
beforeEach(async () => {
userId = new Date().getTime()
let response = await request(server)
.post('/v1/hampers')
.set('Content-Type', 'application/json')
.send({
entity_type: 'credit',
latitude: 0,
longitude: 0,
user_id: userId,
amount: 5000,
entity_id: 1,
processed: true
})
expect(response.status).toEqual(200)
expect(JSON.parse(response.text)).toHaveProperty('uuid')
})
it("have hampers", async () => {
let response = await request(server)
.post('/v1/hampers')
.set('Content-Type', 'application/json')
.send({
entity_type: 'utility',
latitude: 1,
longitude: 1,
comment: null,
user_id: userId,
amount: -200,
entity_id: 1,
processed: false
})
expect(response.status).toEqual(200)
expect(JSON.parse(response.text)).toHaveProperty('uuid')
})
})
开玩笑不断死去:
Timeout - Async callback was not invoked within the 5000ms timeout
specified by jest.setTimeout.
另一个奇怪的问题是,即使我使用 server.close
,Jest 也不会在测试运行后退出。
第二个问题(似乎在测试运行后挂起(可能是由于您的afterAll
缺乏knex.destroy()
引起的。看到您的路由定义后,我可以解决第一个问题。