nodejs:启动服务器并查找字符串 "server started at 127.0.0.1:8000" 然后开始测试

nodejs: Start server and look for string "server started at 127.0.0.1:8000" and then start the tests

我正在从我的 NodeJS 脚本启动服务器,然后想执行我的测试。但是当我启动服务器时,服务器启动进程不会 return 因为它是 运行ning 并且控制不会 returned 回来。服务器启动,可以在 http://localhost:8000 上访问应用程序。

尝试启动服务器,然后监视 运行 服务器进程的标准输出并查找匹配项“Starting server at 127.0.0.1:8000”,然后继续 运行 测试. 有什么方法可以使用 exec 或 spawn node 命令完成,然后监视所需的字符串以开始我的测试?

基于上一个问题 当 Http://localhost:8000 启动并且 运行ning.

时开始测试轮询

我正在寻找的解决方案是根据标准输出数据字符串匹配启动测试 - “启动开发服务器”。

是的,使用 spawn 并查找字符串,然后 运行 你的测试,监控 SIGTERM 和 SIGINT,然后将它传递给 child。

const {
  spawn
} = require('child_process')

// your cmd to start the server, possibly spawn('python', ['manage.py', 'startserver'])
const server = spawn('node', ['server.js'])

let timer = null
server.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`)

  // look for the string in stdout
  if (data.includes('Starting development server')) {

    console.log('Commencing tests in 2 seconds')
    timer = setTimeout(() => {
      console.log('Run tests')

      // ...

      // tests complete
      setTimeout(() => {
        console.log('Tests completed, shutting down server')
        server.kill('SIGINT')
      }, 2000)
    }, 2000)
  }
})

server.stderr.on('data', (data) => {
  clearTimeout(timer)
  console.error(`stderr: ${data}`)
});

server.on('close', (code) => {
  clearTimeout(timer)
  console.log(`child process exited with code ${code}`);
});

process
  .on('SIGTERM', shutdown('SIGTERM'))
  .on('SIGINT', shutdown('SIGINT'))
  .on('uncaughtException', shutdown('uncaughtException'))

function shutdown(signal) {
  return (err) => {
    console.log(`\n${signal} signal received.`)

    if (err && err !== signal) console.error(err.stack || err)

    console.log('Killing child process.')
    server.kill(signal)
  }
}

结果

node spawn.js 
stdout: Starting development server http://localhost:8000

Commencing tests in 2 seconds
Run tests
Tests completed, shutting down server
stdout: 
SIGINT signal received.

stdout: Closing HTTP server.

stdout: HTTP server closed.

child process exited with code 0

使用的测试服务器脚本如下,注意上面它正在传回它收到的 SIGINT 信号。

const express = require('express')
const app = express()
const port = 8000

app.get('/', (req, res) => res.send('Hello World!'))

const server = app.listen(port, () => console.log(`Starting development server http://localhost:${port}`))


process
  .on('SIGTERM', shutdown('SIGTERM'))
  .on('SIGINT', shutdown('SIGINT'))
  .on('uncaughtException', shutdown('uncaughtException'))

function shutdown(signal) {
  return (err) => {
    console.log(`\n${signal} signal received.`)

    if (err && err !== signal) console.error(err.stack || err)

    console.log('Closing HTTP server.')
    server.close(() => {
      console.log('HTTP server closed.')
      //
      process.exit(err && err !== signal ? 1 : 0)
    })
  }
}