在我的测试中,我使用 require('child_process').exec 运行“npm run start-app”,它启动了一个 webpack-dev-server。测试运行后,我想终止已启动的进程。
目前,我可以在直接运行“mochatests.js”时成功终止进程。但是,当我使用调用“mochatests.js”的“npm runtests”运行测试时,该进程不会被终止。这是因为 Node 进程阻止我杀死该进程吗?
我通过使用 ps-tree 发现 pid 并根据操作系统使用kill -9 或taskkill 来终止进程。
test.after(function () {
psTree(appStartProcess.pid, function (err, children) {
if(/^win/.test(process.platform)) {
for(var i = 0; i < children.length; i++) {
exec('taskkill /pid ' + children[i].PID + ' /T /F');
}
} else{
cp.spawn('kill', ['-9'].concat(children.map(function (p) {
return p.PID;
})));
}
});
});
如有任何建议,我们将不胜感激!
最佳答案
您可以使用ChildProcess
在我们测试之后由 spawn
返回,然后kill
它。
假设以下服务器充当正在运行的进程:
#!/usr/bin/env node
require('http').createServer((_, res) => {
res.end('Hi from process')
}).listen(3000, console.log)
您的测试可能如下所示:
const { exec } = require('child_process')
// this would typically be done in a separate helper
// that mocha executes before your tests
before(function (done) {
// `this` is the shared mocha execution context
this.runningProcess = exec('test/server.js')
setTimeout(done, 500)
})
after(function () {
this.runningProcess.kill()
})
describe('my tests', () => {
it('properly initializes process', (done) => {
require('http').get({
port: 3000,
agent: false
}, (res) => {
let data = ''
res
.setEncoding('utf8')
.on('data', chunk => data += chunk)
.on('end', () => {
require('assert')(data === 'Hi from process')
done()
})
})
})
})
或者,您可以使用 mocha 之外的东西(例如启动服务器、运行 mocha,然后关闭服务器的自定义脚本),但概念本质上是相同的。
关于node.js - 如何在摩卡测试中杀死 Node 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626193/