【问题标题】:How to synchronously wait for express.js HTTP server to close after a listen call?如何在监听调用后同步等待 express.js HTTP 服务器关闭?
【发布时间】: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


    【解决方案1】:

    好的,我应该早点学习更多的承诺,这是令人满意的方法:

    #!/usr/bin/env node
    (async () => {
    const express = require('express')
    const app = express()
    app.get('/', (req, res) => {
      res.send('hello world')
    })
    await new Promise((resolve, reject) => {
      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()
        resolve()
      })
    })
    console.log('After listen')
    })()
    

    这基本上与您可以用来同步 JavaScript 中的任何其他异步回调函数的通用模式相同,例如对于 HTTP 请求:Synchronous request in Node.js

    在这里,我说明了一个更完整的测试设置,它还发出 HTTP 请求并断言事物:What's the best way to test express.js API

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多