Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Capture and assert on error output. #174

Merged
merged 1 commit into from
Apr 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions packages/build/src/test/js-transform_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import * as path from 'path';
import stripIndent = require('strip-indent');

import {jsTransform} from '../js-transform';
import {interceptOutput} from './util';

suite('jsTransform', () => {
const rootDir =
Expand Down Expand Up @@ -66,10 +67,13 @@ suite('jsTransform', () => {
invalidJs, {compileToEs5: true, softSyntaxError: false}));
});

test('do not throw when softSyntaxError is true', () => {
assert.equal(
jsTransform(invalidJs, {compileToEs5: true, softSyntaxError: true}),
invalidJs);
test('do not throw when softSyntaxError is true', async () => {
const output = await interceptOutput(async () => {
assert.equal(
jsTransform(invalidJs, {compileToEs5: true, softSyntaxError: true}),
invalidJs);
});
assert.include(output, '[polymer-build]: failed to parse JavaScript:');
});
});

Expand Down
38 changes: 38 additions & 0 deletions packages/build/src/test/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,41 @@ const transformMapValues =
<K, V1, V2>(map: Map<K, V1>, transform: (val: V1) => V2): Map<K, V2> =>
new Map([...map.entries()].map(
([key, val]): [K, V2] => [key, transform(val)]));

/**
* Calls the given async function and captures all console.log and friends
* output while until the returned Promise settles.
*
* Does not capture plylog, which doesn't seem to be very easy to intercept.
*
* TODO(rictic): this function is shared across many of our packages,
* put it in a shared package instead.
*/
export async function interceptOutput(captured: () => Promise<void>):
Promise<string> {
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
const buffer: string[] = [];
const capture = (...args: any[]) => {
buffer.push(args.join(' '));
};
console.log = capture;
console.error = capture;
console.warn = capture;
const restoreAndGetOutput = () => {
console.log = originalLog;
console.error = originalError;
console.warn = originalWarn;
return buffer.join('\n');
};
try {
await captured();
} catch (err) {
const output = restoreAndGetOutput();
console.error(output);
throw err;
}

return restoreAndGetOutput();
}