【发布时间】:2022-01-25 11:38:50
【问题描述】:
为了自动化我的 Express.js 测试,我想确保在每个测试决定结果时测试已经运行完毕。
考虑这种情况的简化模型:
main.js
#!/usr/bin/env node
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
const server = app.listen(3000, function () {
// I would run tests here, which is the 'listen' event.
console.log('Server started')
// After the tests, I will close the server from here.
this.close()
})
// I want to make sure that this runs only after the asserts were done,
// otherwise the test would miss possible failures.
console.log('After listen')
package.json
{
"name": "tmp",
"version": "1.0.0",
"dependencies": {
"express": "4.17.1"
}
}
运行main 产生:
After listen
Server started
因为服务器必须异步开始监听连接,所以After listen首先运行。但我想拥有:
Server started
After listen
我知道'close' 事件可以让我写:
#!/usr/bin/env node
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('hello world')
})
const server = app.listen(3000, function () {
// I would run tests here, which is the 'listen' event.
console.log('Server started')
// After the tests, I will close the server from here.
this.close()
})
server.on('close', () => {
console.log('After listen')
})
但这只是将问题进一步转移到测试基础设施,它必须确保它能够等待After listen 发生。是的,在 Mocha 中,done() 可以做到这一点,但最好有一些更简单、更与测试系统无关的东西。
在 Node.js 14.15.0 上测试。
相关:
【问题讨论】:
标签: express