diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dc41106eef2..225de647270c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - `[babel-preset-jest]` Add `@babel/plugin-syntax-bigint` ([#8382](https://github.com/facebook/jest/pull/8382)) - `[expect]` Add `BigInt` support to `toBeGreaterThan`, `toBeGreaterThanOrEqual`, `toBeLessThan` and `toBeLessThanOrEqual` ([#8382](https://github.com/facebook/jest/pull/8382)) - `[expect, jest-matcher-utils]` Display change counts in annotation lines ([#9035](https://github.com/facebook/jest/pull/9035)) +- `[expect, jest-snapshot]` Support custom inline snapshot matchers ([#9278](https://github.com/facebook/jest/pull/9278)) - `[jest-config]` Throw the full error message and stack when a Jest preset is missing a dependency ([#8924](https://github.com/facebook/jest/pull/8924)) - `[jest-config]` [**BREAKING**] Set default display name color based on runner ([#8689](https://github.com/facebook/jest/pull/8689)) - `[jest-config]` Merge preset globals with project globals ([#9027](https://github.com/facebook/jest/pull/9027)) diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index 9c58b49a97fc..af1721ebf32a 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -233,6 +233,28 @@ exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`; */ ``` +It's also possible to create custom matchers for inline snapshots, the snapshots will be correctly added to the custom matchers. However, inline snapshot will always try to append to the first argument or the second when the first argument is the property matcher, so it's not possible to accept custom arguments in the custom matchers. + +```js +const {toMatchInlineSnapshot} = require('jest-snapshot'); + +expect.extend({ + toMatchTrimmedInlineSnapshot(received) { + return toMatchInlineSnapshot.call(this, received.substring(0, 10)); + }, +}); + +it('stores only 10 characters', () => { + expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot(); + /* + The snapshot will be added inline like + expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot( + `"extra long"` + ); + */ +}); +``` + ### `expect.anything()` `expect.anything()` matches anything but `null` or `undefined`. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument: diff --git a/e2e/__tests__/__snapshots__/toMatchInlineSnapshot.test.ts.snap b/e2e/__tests__/__snapshots__/toMatchInlineSnapshot.test.ts.snap index 67f659ceb42c..b2d7e3c2a5a1 100644 --- a/e2e/__tests__/__snapshots__/toMatchInlineSnapshot.test.ts.snap +++ b/e2e/__tests__/__snapshots__/toMatchInlineSnapshot.test.ts.snap @@ -120,6 +120,41 @@ test('handles property matchers', () => { `; +exports[`multiple custom matchers and native matchers: multiple matchers 1`] = ` +const {toMatchInlineSnapshot} = require('jest-snapshot'); +expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, + toMatchCustomInlineSnapshot2(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, +}); +test('inline snapshots', () => { + expect({apple: 'value 1'}).toMatchCustomInlineSnapshot(\` + Object { + "apple": "value 1", + } + \`); + expect({apple: 'value 2'}).toMatchInlineSnapshot(\` + Object { + "apple": "value 2", + } + \`); + expect({apple: 'value 3'}).toMatchCustomInlineSnapshot2(\` + Object { + "apple": "value 3", + } + \`); + expect({apple: 'value 4'}).toMatchInlineSnapshot(\` + Object { + "apple": "value 4", + } + \`); +}); + +`; + exports[`removes obsolete external snapshots: external snapshot cleaned 1`] = ` test('removes obsolete external snapshots', () => { expect('1').toMatchInlineSnapshot(\`"1"\`); @@ -160,6 +195,71 @@ test('inline snapshots', async () => { `; +exports[`supports custom matchers with property matcher: custom matchers with property matcher 1`] = ` +const {toMatchInlineSnapshot} = require('jest-snapshot'); +expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, + toMatchUserInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call( + this, + received, + { + createdAt: expect.any(Date), + id: expect.any(Number), + }, + ...args + ); + }, +}); +test('inline snapshots', () => { + const user = { + createdAt: new Date(), + id: Math.floor(Math.random() * 20), + name: 'LeBron James', + }; + expect(user).toMatchCustomInlineSnapshot( + { + createdAt: expect.any(Date), + id: expect.any(Number), + }, + \` + Object { + "createdAt": Any, + "id": Any, + "name": "LeBron James", + } + \` + ); + expect(user).toMatchUserInlineSnapshot(\` + Object { + "createdAt": Any, + "id": Any, + "name": "LeBron James", + } + \`); +}); + +`; + +exports[`supports custom matchers: custom matchers 1`] = ` +const {toMatchInlineSnapshot} = require('jest-snapshot'); +expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, +}); +test('inline snapshots', () => { + expect({apple: 'original value'}).toMatchCustomInlineSnapshot(\` + Object { + "apple": "original value", + } + \`); +}); + +`; + exports[`writes snapshots with non-literals in expect(...) 1`] = ` it('works with inline snapshots', () => { expect({a: 1}).toMatchInlineSnapshot(\` diff --git a/e2e/__tests__/toMatchInlineSnapshot.test.ts b/e2e/__tests__/toMatchInlineSnapshot.test.ts index bea20f9baf04..a58cb03fffae 100644 --- a/e2e/__tests__/toMatchInlineSnapshot.test.ts +++ b/e2e/__tests__/toMatchInlineSnapshot.test.ts @@ -266,3 +266,97 @@ test('handles mocking native modules prettier relies on', () => { expect(stderr).toMatch('1 snapshot written from 1 test suite.'); expect(exitCode).toBe(0); }); + +test('supports custom matchers', () => { + const filename = 'custom-matchers.test.js'; + const test = ` + const { toMatchInlineSnapshot } = require('jest-snapshot'); + expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + } + }); + test('inline snapshots', () => { + expect({apple: "original value"}).toMatchCustomInlineSnapshot(); + }); + `; + + writeFiles(TESTS_DIR, {[filename]: test}); + const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]); + const fileAfter = readFile(filename); + expect(stderr).toMatch('1 snapshot written from 1 test suite.'); + expect(exitCode).toBe(0); + expect(wrap(fileAfter)).toMatchSnapshot('custom matchers'); +}); + +test('supports custom matchers with property matcher', () => { + const filename = 'custom-matchers-with-property-matcher.test.js'; + const test = ` + const { toMatchInlineSnapshot } = require('jest-snapshot'); + expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, + toMatchUserInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call( + this, + received, + { + createdAt: expect.any(Date), + id: expect.any(Number), + }, + ...args + ); + }, + }); + test('inline snapshots', () => { + const user = { + createdAt: new Date(), + id: Math.floor(Math.random() * 20), + name: 'LeBron James', + }; + expect(user).toMatchCustomInlineSnapshot({ + createdAt: expect.any(Date), + id: expect.any(Number), + }); + expect(user).toMatchUserInlineSnapshot(); + }); + `; + + writeFiles(TESTS_DIR, {[filename]: test}); + const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]); + const fileAfter = readFile(filename); + expect(stderr).toMatch('2 snapshots written from 1 test suite.'); + expect(exitCode).toBe(0); + expect(wrap(fileAfter)).toMatchSnapshot( + 'custom matchers with property matcher', + ); +}); + +test('multiple custom matchers and native matchers', () => { + const filename = 'multiple-matchers.test.js'; + const test = ` + const { toMatchInlineSnapshot } = require('jest-snapshot'); + expect.extend({ + toMatchCustomInlineSnapshot(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, + toMatchCustomInlineSnapshot2(received, ...args) { + return toMatchInlineSnapshot.call(this, received, ...args); + }, + }); + test('inline snapshots', () => { + expect({apple: "value 1"}).toMatchCustomInlineSnapshot(); + expect({apple: "value 2"}).toMatchInlineSnapshot(); + expect({apple: "value 3"}).toMatchCustomInlineSnapshot2(); + expect({apple: "value 4"}).toMatchInlineSnapshot(); + }); + `; + + writeFiles(TESTS_DIR, {[filename]: test}); + const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]); + const fileAfter = readFile(filename); + expect(stderr).toMatch('4 snapshots written from 1 test suite.'); + expect(exitCode).toBe(0); + expect(wrap(fileAfter)).toMatchSnapshot('multiple matchers'); +}); diff --git a/packages/expect/src/index.ts b/packages/expect/src/index.ts index 3bb418c79298..a99fa819d0e3 100644 --- a/packages/expect/src/index.ts +++ b/packages/expect/src/index.ts @@ -297,7 +297,7 @@ const makeThrowingMatcher = ( } }; - const handlError = (error: Error) => { + const handleError = (error: Error) => { if ( matcher[INTERNAL_MATCHER_FLAG] === true && !(error instanceof JestAssertionError) && @@ -314,7 +314,15 @@ const makeThrowingMatcher = ( let potentialResult: ExpectationResult; try { - potentialResult = matcher.call(matcherContext, actual, ...args); + potentialResult = + matcher[INTERNAL_MATCHER_FLAG] === true + ? matcher.call(matcherContext, actual, ...args) + : // It's a trap specifically for inline snapshot to capture this name + // in the stack trace, so that it can correctly get the custom matcher + // function call. + (function __EXTERNAL_MATCHER_TRAP__() { + return matcher.call(matcherContext, actual, ...args); + })(); if (isPromise(potentialResult)) { const asyncResult = potentialResult as AsyncExpectationResult; @@ -325,14 +333,14 @@ const makeThrowingMatcher = ( return asyncResult .then(aResult => processResult(aResult, asyncError)) - .catch(error => handlError(error)); + .catch(error => handleError(error)); } else { const syncResult = potentialResult as SyncExpectationResult; return processResult(syncResult); } } catch (error) { - return handlError(error); + return handleError(error); } }; diff --git a/packages/jest-snapshot/src/State.ts b/packages/jest-snapshot/src/State.ts index af3e659ab54f..da0ee884a8db 100644 --- a/packages/jest-snapshot/src/State.ts +++ b/packages/jest-snapshot/src/State.ts @@ -14,6 +14,7 @@ import { getSnapshotData, keyToTestName, removeExtraLineBreaks, + removeLinesBeforeExternalMatcherTrap, saveSnapshotFile, serialize, testNameToKey, @@ -104,7 +105,9 @@ export default class SnapshotState { this._dirty = true; if (options.isInline) { const error = options.error || new Error(); - const lines = getStackTraceLines(error.stack || ''); + const lines = getStackTraceLines( + removeLinesBeforeExternalMatcherTrap(error.stack || ''), + ); const frame = getTopFrame(lines); if (!frame) { throw new Error( diff --git a/packages/jest-snapshot/src/__tests__/utils.test.ts b/packages/jest-snapshot/src/__tests__/utils.test.ts index 4fcdf587da1a..df0845440f49 100644 --- a/packages/jest-snapshot/src/__tests__/utils.test.ts +++ b/packages/jest-snapshot/src/__tests__/utils.test.ts @@ -24,6 +24,7 @@ import { getSnapshotData, keyToTestName, removeExtraLineBreaks, + removeLinesBeforeExternalMatcherTrap, saveSnapshotFile, serialize, testNameToKey, @@ -266,6 +267,43 @@ describe('ExtraLineBreaks', () => { }); }); +describe('removeLinesBeforeExternalMatcherTrap', () => { + test('contains external matcher trap', () => { + const stack = `Error: + at SnapshotState._addSnapshot (/jest/packages/jest-snapshot/build/State.js:150:9) + at SnapshotState.match (/jest/packages/jest-snapshot/build/State.js:303:14) + at _toMatchSnapshot (/jest/packages/jest-snapshot/build/index.js:399:32) + at _toThrowErrorMatchingSnapshot (/jest/packages/jest-snapshot/build/index.js:585:10) + at Object.toThrowErrorMatchingInlineSnapshot (/jest/packages/jest-snapshot/build/index.js:504:10) + at Object. (/jest/packages/expect/build/index.js:138:20) + at __EXTERNAL_MATCHER_TRAP__ (/jest/packages/expect/build/index.js:378:30) + at throwingMatcher (/jest/packages/expect/build/index.js:379:15) + at /jest/packages/expect/build/index.js:285:72 + at Object. (/jest/e2e/to-throw-error-matching-inline-snapshot/__tests__/should-support-rejecting-promises.test.js:3:7)`; + + const expected = ` at throwingMatcher (/jest/packages/expect/build/index.js:379:15) + at /jest/packages/expect/build/index.js:285:72 + at Object. (/jest/e2e/to-throw-error-matching-inline-snapshot/__tests__/should-support-rejecting-promises.test.js:3:7)`; + + expect(removeLinesBeforeExternalMatcherTrap(stack)).toBe(expected); + }); + + test("doesn't contain external matcher trap", () => { + const stack = `Error: + at SnapshotState._addSnapshot (/jest/packages/jest-snapshot/build/State.js:150:9) + at SnapshotState.match (/jest/packages/jest-snapshot/build/State.js:303:14) + at _toMatchSnapshot (/jest/packages/jest-snapshot/build/index.js:399:32) + at _toThrowErrorMatchingSnapshot (/jest/packages/jest-snapshot/build/index.js:585:10) + at Object.toThrowErrorMatchingInlineSnapshot (/jest/packages/jest-snapshot/build/index.js:504:10) + at Object. (/jest/packages/expect/build/index.js:138:20) + at throwingMatcher (/jest/packages/expect/build/index.js:379:15) + at /jest/packages/expect/build/index.js:285:72 + at Object. (/jest/e2e/to-throw-error-matching-inline-snapshot/__tests__/should-support-rejecting-promises.test.js:3:7)`; + + expect(removeLinesBeforeExternalMatcherTrap(stack)).toBe(stack); + }); +}); + describe('DeepMerge with property matchers', () => { const matcher = expect.any(String); diff --git a/packages/jest-snapshot/src/inline_snapshots.ts b/packages/jest-snapshot/src/inline_snapshots.ts index aee39a282d5a..e54d62ba08c6 100644 --- a/packages/jest-snapshot/src/inline_snapshots.ts +++ b/packages/jest-snapshot/src/inline_snapshots.ts @@ -78,6 +78,10 @@ const saveSnapshotsForFile = ( ? prettier.getFileInfo.sync(sourceFilePath).inferredParser : (config && config.parser) || simpleDetectParser(sourceFilePath); + // Record the matcher names seen in insertion parser and pass them down one + // by one to formatting parser. + const snapshotMatcherNames: Array = []; + // Insert snapshots using the custom parser API. After insertion, the code is // formatted, except snapshot indentation. Snapshots cannot be formatted until // after the initial format because we don't know where the call expression @@ -85,14 +89,23 @@ const saveSnapshotsForFile = ( const newSourceFile = prettier.format(sourceFile, { ...config, filepath: sourceFilePath, - parser: createInsertionParser(snapshots, inferredParser, babelTraverse), + parser: createInsertionParser( + snapshots, + snapshotMatcherNames, + inferredParser, + babelTraverse, + ), }); // Format the snapshots using the custom parser API. const formattedNewSourceFile = prettier.format(newSourceFile, { ...config, filepath: sourceFilePath, - parser: createFormattingParser(inferredParser, babelTraverse), + parser: createFormattingParser( + snapshotMatcherNames, + inferredParser, + babelTraverse, + ), }); if (formattedNewSourceFile !== sourceFile) { @@ -120,7 +133,7 @@ const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file); const indent = (snapshot: string, numIndents: number, indentation: string) => { const lines = snapshot.split('\n'); - // Prevent re-identation of inline snapshots. + // Prevent re-indentation of inline snapshots. if ( lines.length >= 2 && lines[1].startsWith(indentation.repeat(numIndents + 1)) @@ -166,6 +179,7 @@ const getAst = ( // This parser inserts snapshots into the AST. const createInsertionParser = ( snapshots: Array, + snapshotMatcherNames: Array, inferredParser: string, babelTraverse: Function, ) => ( @@ -198,6 +212,9 @@ const createInsertionParser = ( 'Jest: Multiple inline snapshots for the same call are not supported.', ); } + + snapshotMatcherNames.push(callee.property.name); + const snapshotIndex = args.findIndex( ({type}) => type === 'TemplateLiteral', ); @@ -228,6 +245,7 @@ const createInsertionParser = ( // This parser formats snapshots to the correct indentation. const createFormattingParser = ( + snapshotMatcherNames: Array, inferredParser: string, babelTraverse: Function, ) => ( @@ -244,7 +262,7 @@ const createFormattingParser = ( if ( callee.type !== 'MemberExpression' || callee.property.type !== 'Identifier' || - callee.property.name !== 'toMatchInlineSnapshot' || + callee.property.name !== snapshotMatcherNames[0] || !callee.loc || callee.computed ) { @@ -264,6 +282,8 @@ const createFormattingParser = ( return; } + snapshotMatcherNames.shift(); + const useSpaces = !options.useTabs; snapshot = indent( snapshot, diff --git a/packages/jest-snapshot/src/utils.ts b/packages/jest-snapshot/src/utils.ts index 8d9f6a8374f4..602f6812a718 100644 --- a/packages/jest-snapshot/src/utils.ts +++ b/packages/jest-snapshot/src/utils.ts @@ -136,6 +136,20 @@ export const removeExtraLineBreaks = (string: string): string => ? string.slice(1, -1) : string; +export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => { + const lines = stack.split('\n'); + + for (let i = 0; i < lines.length; i += 1) { + // It's a function name specified in `packages/expect/src/index.ts` + // for external custom matchers. + if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) { + return lines.slice(i + 1).join('\n'); + } + } + + return stack; +}; + const escapeRegex = true; const printFunctionName = false;