testingchild_process.exec标准输出

我试图用摩卡testingsubprocess的输出。

我的testing看起来像这样:

var should = require("should"), exec = require("child_process").exec; describe('users', function() { describe('andrei', function() { exec('id andrei', function(error, stdout, stderr) { it('should be part of group dev', function() { stdout.should.containEql('dev'); }) }) }) }) 

我遇到的问题是it永远不会被执行。

我可以交换代码,把exec放在里面,然后用done来确保按照正确的顺序运行,但是这意味着我将不得不为每个testing运行相同的exec,标准输出。

我怎样才能有多个it声明对儿童进程的标准输出?

摩卡不是devise来运行你在你的问题中显示的代码。 你可以把它想成两个阶段。 在第一阶段,它读取所有的testing文件并执行它们。 它知道你的套件中有什么testing,是通过执行所有callback来立即describe ,每次遇到it时logging下来就是testing。 在第二阶段,它进行testing。 所以为了让摩卡能够看到一个testing,它必须在第一阶段看到it 。 你显示的代码将防止这种情况发生。

我怎样才能有多个它的声明对儿童进程的标准输出?

这听起来像你正在争取一个断言。 我不确定你为什么要在你的具体情况下这样做。 在同一个testing中的多个断言是完全正确的。 无论如何,如果你必须这样做,那么你可以使用一个before钩子:

 var should = require("should"), exec = require("child_process").exec; describe('users', function() { describe('andrei', function() { var captured_stdout; before(function (done) { exec('id andrei', function (error, stdout, stderr) { if (error) done(error); // Handle errors. captured_stdout = stdout; done(); }); }); it('should be part of group dev', function() { captured_stdout.should.containEql('dev'); }); }); }); 

传递给before的callback将在父级describe所有testingdescribe之前运行。 要被testing的数据在capture_stdout中被captured_stdout ,然后testing可以全部访问它并对其进行testing。

多年以后,摩卡已经成熟并支持testingasynchronous代码 。

只需简单的添加一个callback函数(通常命名为done ),Mocha就会知道它应该等待这个函数被调用来完成testing。

 const should = require("should"), { exec } = require("child_process"); describe('users', function() { describe('andrei', function() { it('should be part of group dev', function(done) { exec('id andrei', function(error, stdout, stderr) { stdout.should.containEql('dev'); done(); }) }) }) })