Saturday, 29 September 2018

'This socket is closed' when stdout is listened in Mocha test

This test

it.only('should not throw', () => {
    var output = '';

    function callback(data) {
        output += data.toString();
    }

    process.stdout.on('data', callback); // error is thrown at this line
    // ...
    process.stdout.removeListener('data', callback);
})

throws an error:

Error: This socket is closed                                                                           
    at WriteStream.Socket._writeGeneric (net.js:679:19)                                                
    at WriteStream.Socket._write (net.js:730:8)                                                        
    at doWrite (_stream_writable.js:331:12)                                                            
    at writeOrBuffer (_stream_writable.js:317:5)                                                       
    at WriteStream.Writable.write (_stream_writable.js:243:11)                                         
    at WriteStream.Socket.write (net.js:657:40)                                                        
    at Console.log (console.js:43:16)                                                                  
    at Runner.<anonymous> (node_modules\mocha\lib\reporters\spec.js:80:13)
    at emitTwo (events.js:111:20)                                                                      
    at Runner.emit (events.js:191:7)                                                                   
    at Runner.fail (node_modules\mocha\lib\runner.js:251:8)               
    at Runner.uncaught (node_modules\mocha\lib\runner.js:757:8)           
    at process.uncaught (node_modules\mocha\lib\runner.js:839:10)         
    at emitOne (events.js:96:13)                                                                       
    at process.emit (events.js:188:7)                                                                  
    at process._fatalException (bootstrap_node.js:297:26)                                              

Where node_modules\mocha\lib\reporters\spec.js:80:13 are these Mocha lines:

  runner.on('fail', function(test) {
    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
  });

It's supposed to test code that outputs to process.stdout with spawn, but I wasn't able to get to this part; the error is thrown instantly on process.stdout.on('data', ...) call.

The problem persists with latest Mocha (5.2.0) and default configuration, a reporter in use doesn't affect the result.

What is going on and how can process.stdout be listened? If this is impossible, how can stdout from spawned process be tested in Mocha otherwise?



from 'This socket is closed' when stdout is listened in Mocha test

No comments:

Post a Comment