Skip to content

Commit c45e347

Browse files
committed
test: fix hijackStdout behavior in console
`console.log` and some other function will swallow the exception in `stdout.write`. So an asynchronous exception is needed, or `common.hijackStdout` won't detect some exception. Refs: https://github.com/nodejs/node/blob/v8.2.1/lib/console.js#L87
1 parent ff65a2e commit c45e347

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

test/common/index.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,14 @@ function hijackStdWritable(name, listener) {
801801

802802
stream.writeTimes = 0;
803803
stream.write = function(data, callback) {
804-
listener(data);
804+
try {
805+
listener(data);
806+
} catch(e) {
807+
process.nextTick(function() {
808+
throw e;
809+
});
810+
}
811+
805812
_write.call(stream, data, callback);
806813
stream.writeTimes++;
807814
};

test/parallel/test-common.js

+20
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,23 @@ const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ];
108108
common[`restoreStd${txt}`]();
109109
assert.strictEqual(originalWrite, stream.write);
110110
});
111+
112+
// hijackStderr and hijackStdout again
113+
// for console
114+
[ 'err', 'out' ].forEach((txt) => {
115+
common[`hijackStd${txt}`](common.mustCall(function(data) {
116+
assert.strictEqual(data, 'test\n');
117+
118+
// throw an error
119+
throw new Error(`console ${txt} error`);
120+
}));
121+
122+
console[txt === 'err' ? 'error' : 'log']('test');
123+
common[`restoreStd${txt}`]();
124+
});
125+
126+
let uncaughtTimes = 0;
127+
process.on('uncaughtException', common.mustCallAtLeast(function(e) {
128+
assert.strictEqual(e instanceof Error, true);
129+
assert.strictEqual(e.message, `console ${([ 'err', 'out' ])[uncaughtTimes++]} error`);
130+
}, 2));

0 commit comments

Comments
 (0)