2017-10-07 69 views
0

在我的测试中,我使用require('child_process')。exec运行启动webpack-dev-server的“npm run start-app”。我的测试运行后,我想杀死我已经开始的进程。如何杀死摩卡测试中的节点进程

目前我能够直接运行“mocha tests.js”时成功终止进程。但是,当我使用调用“mocha tests.js”的“npm run tests”运行测试时,该过程不会被终止。这是因为节点进程阻止我杀死进程?

我通过使用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; 
       }))); 
      } 
     }); 
    }); 

任何建议将不胜感激!

+0

我已经用开始一个进程的全局'之前'和'之后'块解决了这个问题(并存储了一些对它的引用),然后将其杀死。 –

+0

嘿尼克基本上是我在做什么,当我直接运行测试时工作。一旦我使用npm run test作为包装,进程不会被杀死....你是如何使用npm run运行你的测试的? – RyanCW

+0

嗯,我可能会移动的方向创建一个事件发射器或套接字侦听套接字中的kill子命令,干净退出命令时发出。 – agm1984

回答

0

您可以使用我们测试后spawn返回的ChildProcess之后的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() 
     }) 
    }) 
    }) 
}) 

或者,你可以使用的东西摩卡之外(例如启动服务器的自定义脚本,运行摩卡,然后关闭服务器),但概念基本相同。