2017-10-07 66 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() 
     }) 
    }) 
    }) 
}) 

或者,你可以使用的東西摩卡之外(例如啓動服務器的自定義腳本,運行摩卡,然後關閉服務器),但概念基本相同。