Skip to content

Commit

Permalink
Intercept process.stdout and process.stderr
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Aug 6, 2020
1 parent c95abca commit e470822
Show file tree
Hide file tree
Showing 15 changed files with 179 additions and 41 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

- `[jest-circus, jest-jasmine2]` Include `failureDetails` property in test results ([#9496](https://github.com/facebook/jest/pull/9496))
- `[jest-each, jest-jasmine, jest-circus]` Add support for .concurrent.each ([#9326](https://github.com/facebook/jest/pull/9326))
- `[jest-runner]` [**BREAKING**] Intercept `process.stdout` and `process.stderr` in the same way as `console` methods ([#6524](https://github.com/facebook/jest/pull/6524))

### Fixes

Expand Down
62 changes: 56 additions & 6 deletions e2e/__tests__/__snapshots__/console.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ PASS __tests__/console.test.js
| ^
15 |
16 | console.error('This is an error message.');
17 | });
17 |
at Object.warn (__tests__/console.test.js:14:11)
Expand All @@ -34,10 +34,28 @@ PASS __tests__/console.test.js
15 |
> 16 | console.error('This is an error message.');
| ^
17 | });
18 |
17 |
18 | process.stdout.write('write directly to stdout');
19 |
at Object.error (__tests__/console.test.js:16:11)
process.stdout.write
write directly to stdout
at Object.write (__tests__/console.test.js:18:18)
process.stderr.write
write directly to stderr
18 | process.stdout.write('write directly to stdout');
19 |
> 20 | process.stderr.write('write directly to stderr');
| ^
21 | });
22 |
at Object.write (__tests__/console.test.js:20:18)
`;

exports[`console printing 2`] = `
Expand Down Expand Up @@ -68,7 +86,7 @@ exports[`console printing with --verbose 1`] = `
| ^
15 |
16 | console.error('This is an error message.');
17 | });
17 |
at Object.warn (__tests__/console.test.js:14:11)
Expand All @@ -79,11 +97,27 @@ exports[`console printing with --verbose 1`] = `
15 |
> 16 | console.error('This is an error message.');
| ^
17 | });
18 |
17 |
18 | process.stdout.write('write directly to stdout');
19 |
at Object.error (__tests__/console.test.js:16:11)
process.stdout.write
write directly to stdout
at Object.write (__tests__/console.test.js:18:18)
process.stderr.write
write directly to stderr
18 | process.stdout.write('write directly to stdout');
19 |
> 20 | process.stderr.write('write directly to stderr');
| ^
21 | });
22 |
at Object.write (__tests__/console.test.js:20:18)
`;
exports[`console printing with --verbose 2`] = `
Expand Down Expand Up @@ -166,6 +200,14 @@ exports[`respects --noStackTrace 1`] = `
at Object.error (__tests__/console.test.js:16:11)
process.stdout.write
write directly to stdout
at Object.write (__tests__/console.test.js:18:18)
process.stderr.write
write directly to stderr
at Object.write (__tests__/console.test.js:20:18)
`;
exports[`respects --noStackTrace 2`] = `
Expand Down Expand Up @@ -202,6 +244,14 @@ exports[`respects noStackTrace in config 1`] = `
at Object.error (__tests__/console.test.js:16:11)
process.stdout.write
write directly to stdout
at Object.write (__tests__/console.test.js:18:18)
process.stderr.write
write directly to stderr
at Object.write (__tests__/console.test.js:20:18)
`;
exports[`respects noStackTrace in config 2`] = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ PASS __tests__/console.test.js
14 | });
15 |
at BufferedConsole.log (../../packages/jest-console/build/BufferedConsole.js:201:10)
at BufferedConsole.log (../../packages/jest-console/build/BufferedConsole.js:202:10)
at log (__tests__/console.test.js:12:13)
`;
4 changes: 4 additions & 0 deletions e2e/console/__tests__/console.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ test('works just fine', () => {
console.warn('This is a warning message.');

console.error('This is an error message.');

process.stdout.write('write directly to stdout');

process.stderr.write('write directly to stderr');
});
9 changes: 6 additions & 3 deletions packages/jest-console/src/BufferedConsole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import chalk = require('chalk');
import {ErrorWithStack, formatTime} from 'jest-util';
import type {
ConsoleBuffer,
LogApi,
LogCounters,
LogMessage,
LogTimers,
Expand All @@ -24,11 +25,10 @@ export default class BufferedConsole extends Console {
private _timers: LogTimers;
private _groupDepth: number;

constructor() {
const buffer: ConsoleBuffer = [];
constructor(buffer: ConsoleBuffer) {
super({
write: (message: string) => {
BufferedConsole.write(buffer, 'log', message, null);
BufferedConsole.write(buffer, 'log', message, null, 'console');

return true;
},
Expand All @@ -44,6 +44,7 @@ export default class BufferedConsole extends Console {
type: LogType,
message: LogMessage,
level?: number | null,
api: LogApi = 'console',
): ConsoleBuffer {
const stackLevel = level != null ? level : 2;
const rawStack = new ErrorWithStack(undefined, BufferedConsole.write).stack;
Expand All @@ -57,6 +58,7 @@ export default class BufferedConsole extends Console {
.join('\n');

buffer.push({
api,
message,
origin,
type,
Expand All @@ -71,6 +73,7 @@ export default class BufferedConsole extends Console {
type,
' '.repeat(this._groupDepth) + message,
3,
'console',
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('CustomConsole', () => {
};

beforeEach(() => {
_console = new BufferedConsole(() => null);
_console = new BufferedConsole([]);
});

describe('assert', () => {
Expand Down
7 changes: 3 additions & 4 deletions packages/jest-console/src/getConsoleOutput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,21 @@ export default (
const TITLE_INDENT = verbose ? ' ' : ' ';
const CONSOLE_INDENT = TITLE_INDENT + ' ';

const logEntries = buffer.reduce((output, {type, message, origin}) => {
const logEntries = buffer.reduce((output, {api, type, message, origin}) => {
message = message
.split(/\n/)
.map(line => CONSOLE_INDENT + line)
.join('\n');

let typeMessage = 'console.' + type;
let typeMessage = `${api}.${type}`;
let noStackTrace = true;
let noCodeFrame = true;

if (type === 'warn') {
message = chalk.yellow(message);
typeMessage = chalk.yellow(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
} else if (type === 'error') {
} else if (type === 'error' || api === 'process.stderr') {
message = chalk.red(message);
typeMessage = chalk.red(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-console/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ export {default as BufferedConsole} from './BufferedConsole';
export {default as CustomConsole} from './CustomConsole';
export {default as NullConsole} from './NullConsole';
export {default as getConsoleOutput} from './getConsoleOutput';
export type {ConsoleBuffer, LogMessage, LogType} from './types';
export type {ConsoleBuffer, LogApi, LogMessage, LogType} from './types';
6 changes: 5 additions & 1 deletion packages/jest-console/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@

export type LogMessage = string;

export type LogApi = 'console' | 'process.stdout' | 'process.stderr';

export type LogEntry = {
api: LogApi;
message: LogMessage;
origin: string;
type: LogType;
Expand All @@ -33,6 +36,7 @@ export type LogType =
| 'info'
| 'log'
| 'time'
| 'warn';
| 'warn'
| 'write';

export type ConsoleBuffer = Array<LogEntry>;
21 changes: 4 additions & 17 deletions packages/jest-core/src/__tests__/run_jest.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,22 @@ import runJest from '../runJest';

jest.mock('@jest/console');

const processErrWriteFn = process.stderr.write;
describe('runJest', () => {
let stderrSpy;
beforeEach(async () => {
process.exit = jest.fn();
process.stderr.write = jest.fn();
process.stderr.write.mockReset();
stderrSpy = jest.spyOn(process.stderr, 'write');
test('when watch is set then print error and exit process', async () => {
jest.spyOn(process, 'exit').mockImplementation(() => {});

await runJest({
changedFilesPromise: Promise.resolve({repos: {git: {size: 0}}}),
changedFilesPromise: Promise.resolve({repos: {git: new Set()}}),
contexts: [],
globalConfig: {testSequencer: '@jest/test-sequencer', watch: true},
onComplete: () => null,
outputStream: {},
startRun: {},
testWatcher: {isInterrupted: () => true},
});
});

afterEach(() => {
process.stderr.write = processErrWriteFn;
});
await new Promise(process.nextTick);

test('when watch is set then exit process', () => {
expect(process.exit).toHaveBeenCalledWith(1);
});

test('when watch is set then an error message is printed', () => {
expect(stderrSpy).toHaveBeenCalled();
});
});
1 change: 1 addition & 0 deletions packages/jest-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"jest-runtime": "^26.2.2",
"jest-util": "^26.2.0",
"jest-worker": "^26.2.1",
"readable-stream": "^3.1.1",
"source-map-support": "^0.5.6",
"throat": "^5.0.0"
},
Expand Down
Loading

0 comments on commit e470822

Please sign in to comment.