|
1 | 1 | import {TestInterface} from 'ava'; |
2 | 2 |
|
| 3 | +type TestContext = {stdoutWrite: any, stderrWrite: any, testOutput: string}; |
| 4 | + |
| 5 | +function wrapOutput(context: TestContext) { |
| 6 | + return (str: any): boolean => { |
| 7 | + if (typeof str === 'string') { |
| 8 | + context.testOutput += str; |
| 9 | + } |
| 10 | + return true; |
| 11 | + } |
| 12 | +} |
| 13 | + |
3 | 14 | export function silenceDebugOutput(test: TestInterface<any>) { |
4 | | - const typedTest = test as TestInterface<{write: any}>; |
| 15 | + const typedTest = test as TestInterface<TestContext>; |
5 | 16 |
|
6 | 17 | typedTest.beforeEach(t => { |
| 18 | + t.context.testOutput = ""; |
| 19 | + |
7 | 20 | const processStdoutWrite = process.stdout.write.bind(process.stdout); |
8 | | - t.context.write = processStdoutWrite; |
9 | | - process.stdout.write = (str: Uint8Array | string, encoding?: any, cb?: (err?: Error) => void) => { |
10 | | - // Core library will directly call process.stdout.write for commands |
11 | | - // We don't want debug output to be included in tests |
12 | | - if (typeof str === "string") { |
13 | | - str = str.replace(/::(info|debug|warning).*/, ''); |
14 | | - if (str.trim() !== "") { |
15 | | - processStdoutWrite(str, encoding, cb); |
16 | | - } |
17 | | - } else { |
18 | | - processStdoutWrite(str, encoding, cb); |
19 | | - } |
20 | | - return true; |
21 | | - }; |
| 21 | + t.context.stdoutWrite = processStdoutWrite; |
| 22 | + process.stdout.write = wrapOutput(t.context); |
| 23 | + |
| 24 | + const processStderrWrite = process.stderr.write.bind(process.stderr); |
| 25 | + t.context.stderrWrite = processStderrWrite; |
| 26 | + process.stderr.write = wrapOutput(t.context); |
22 | 27 | }); |
23 | 28 |
|
24 | | - typedTest.afterEach(t => { |
25 | | - process.stdout.write = t.context.write; |
| 29 | + typedTest.afterEach.always(t => { |
| 30 | + process.stdout.write = t.context.stdoutWrite; |
| 31 | + process.stderr.write = t.context.stderrWrite; |
| 32 | + |
| 33 | + if (!t.passed) { |
| 34 | + process.stdout.write(t.context.testOutput); |
| 35 | + } |
26 | 36 | }); |
27 | 37 | } |
0 commit comments