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

Stringify Errors properly with --json flag #15329

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Features

- [jest-core] Stringify Errors properly with --json flag ([#15329](https://github.com/jestjs/jest/pull/15329))
- `[babel-jest]` Add option `excludeJestPreset` to allow opting out of `babel-preset-jest` ([#15164](https://github.com/jestjs/jest/pull/15164))
- `[jest-circus, jest-cli, jest-config]` Add `waitNextEventLoopTurnForUnhandledRejectionEvents` flag to minimise performance impact of correct detection of unhandled promise rejections introduced in [#14315](https://github.com/jestjs/jest/pull/14315) ([#14681](https://github.com/jestjs/jest/pull/14681))
- `[jest-circus]` Add a `waitBeforeRetry` option to `jest.retryTimes` ([#14738](https://github.com/jestjs/jest/pull/14738))
Expand Down
49 changes: 49 additions & 0 deletions packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import serializeToJSON from '../serializeToJSON';

// populate an object with all basic JavaScript datatypes
const object = {
species: 'capybara',
ok: true,

Check failure on line 13 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected object keys to be in ascending order. 'ok' should be before 'species'
i: ['pull up'],

Check failure on line 14 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected object keys to be in ascending order. 'i' should be before 'ok'
hopOut: {

Check failure on line 15 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected object keys to be in ascending order. 'hopOut' should be before 'i'
atThe: 'after party',
when: new Date('2000-07-14'),
},
chillness: 100,

Check failure on line 19 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected object keys to be in ascending order. 'chillness' should be before 'hopOut'
weight: 9.5,
flaws: null,

Check failure on line 21 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected object keys to be in ascending order. 'flaws' should be before 'weight'
location: undefined,
};

it('serializes regular objects like JSON.stringify', () => {
expect(serializeToJSON(object)).toEqual(JSON.stringify(object));
});

it('serializes errors', () => {
const objectWithError = {
...object,
error: new Error('too cool'),
};
const withError = serializeToJSON(objectWithError);
const withoutError = JSON.stringify(objectWithError);

expect(withoutError).not.toEqual(withError);

expect(withError).toContain(`"message":"too cool"`);

Check failure on line 39 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Strings must use singlequote
expect(withError).toContain(`"name":"Error"`);

Check failure on line 40 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Strings must use singlequote
expect(withError).toContain(`"stack":"Error:`);

Check failure on line 41 in packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts

View workflow job for this annotation

GitHub Actions / Lint

Strings must use singlequote

expect(JSON.parse(withError)).toMatchObject({
error: {
message: 'too cool',
name: 'Error',
},
});
});
35 changes: 35 additions & 0 deletions packages/jest-core/src/lib/serializeToJSON.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* When we're asked to give a JSON output with the --json flag or otherwise,
* some data we need to return don't serialize well with a basic
* `JSON.stringify`, particularly Errors returned in `.openHandles`.
*
* This function handles the extended serialization wanted above.
*/
export default function serializeToJSON(
value: any,

Check failure on line 16 in packages/jest-core/src/lib/serializeToJSON.ts

View workflow job for this annotation

GitHub Actions / Lint

Argument 'value' should be typed with a non-any type
space?: string | number,
): string {
return JSON.stringify(
value,
(_, value) => {
// There might be more in Error, but pulling out just the message, name,
// and stack should be good enough
if (value instanceof Error) {
return {
message: value.message,
name: value.name,
stack: value.stack,
};
}
return value;
},
space,
);
}
6 changes: 4 additions & 2 deletions packages/jest-core/src/runJest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import getNoTestsFoundMessage from './getNoTestsFoundMessage';
import runGlobalHook from './runGlobalHook';
import type {Filter, TestRunData} from './types';
import serializeToJSON from './lib/serializeToJSON';

Check failure on line 38 in packages/jest-core/src/runJest.ts

View workflow job for this annotation

GitHub Actions / Lint

`./lib/serializeToJSON` import should occur before import of `./runGlobalHook`

const getTestPaths = async (
globalConfig: Config.GlobalConfig,
Expand Down Expand Up @@ -111,20 +112,21 @@
runResults = await processor(runResults);
}
if (isJSON) {
const jsonString = serializeToJSON(formatTestResults(runResults));
if (outputFile) {
const cwd = tryRealpath(process.cwd());
const filePath = path.resolve(cwd, outputFile);

fs.writeFileSync(
filePath,
`${JSON.stringify(formatTestResults(runResults))}\n`,
`${jsonString}\n`,
);
outputStream.write(
`Test results written to: ${path.relative(cwd, filePath)}\n`,
);
} else {
process.stdout.write(
`${JSON.stringify(formatTestResults(runResults))}\n`,
`${jsonString}\n`,
);
}
}
Expand Down
Loading