在Node中,如何检查一个特定的对象是否是一个ChildProcess的实例

我试图检查(在unit testing)如果一个特定的对象是一个ChildProcess,但我似乎无法得到该类的引用(这是https://github.com/joyent/node/blob /7c0419730b237dbfa0ec4e6fb33a99ff01825a8f/lib/child_process.js )

我想要做的是类似的东西

selenium = require('selenium-standalone') spawnOptions = { stdio: 'pipe' } seleniumArgs = ['-Dwebdriver.chrome.driver=./node_modules/nodewebkit/nodewebkit/chromedriver'] @server = selenium(spawnOptions, seleniumArgs) expect(server).to.be.an.instanceof(ChildProcess) 

但我似乎并不知道在哪里得到对ChildProcess的引用

更新:基于提供的答案,我现在正在testing使用:

 it 'start()', (done)-> selenium.start.assert_Is_Function() selenium.start -> selenium.server.assert_Is_Not_Null() selenium.server.constructor.assert_Is_Function() selenium.server.constructor.name.assert_Is('ChildProcess') done() 

不幸的是, child_process模块不会导出它的ChildProcess类。 你可以很容易地访问server的构造函数,但是你没有什么可以比较的。

我可以看到两个选项。

检查server的构造函数名是否是ChildProcess

 expect(server).to.have.property('constuctor'); expect(server.constuctor).to.have.property('name', 'ChildProcess'); 

您也可以添加一个检查server.constuctorEventEmitterinheritance

 expect(server).to.be.an.instanceof(require('events').EventEmitter); 

spawn调用中获取ChildProcess

但是,你想确定server是一个ChildProcess而不是一个模拟,那么你可以从spawn调用获取ChildProcess类:

 ChildProcess = require('child_process').spawn('echo').constructor; // use any command 

您将可以使用它来validation您的server对象:

 expect(server).to.be.an.instanceof(ChildProcess); 

如果你不想实际产生任何东西,你可以使用任何不存在的命令。 只要不要忘记指定一个error handling程序来防止child_process抛出一个错误:

 child = require('child_process').spawn('non-existing-command'); child.on('error', function() {}); // empty error handler ChildProcess = child.constructor; 

child_process从节点4.0 child_process暴露ChildProcess类。

 var ChildProcess = require('child_process').ChildProcess expect(server).to.be.an.instanceof(ChildProcess) 

在PR中添加: https : //github.com/nodejs/node/pull/1760