From 4de5da7a56c670ad5af4c8e6fa56fc34dffbfa62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ari=20Perkki=C3=B6?= Date: Thu, 5 May 2022 00:02:58 +0300 Subject: [PATCH] fix(inline-snapshots): detect linebreaks (#1232) * style: fix typo * test(inline-snapshot): add test for nested object * fix(inline-snapshots): detect linebreaks --- .../src/integrations/snapshot/port/utils.ts | 20 ++++++++++++----- test/core/test/snapshot-inline.test.ts | 22 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/packages/vitest/src/integrations/snapshot/port/utils.ts b/packages/vitest/src/integrations/snapshot/port/utils.ts index a16f9091f0c1..26fee21bbbbd 100644 --- a/packages/vitest/src/integrations/snapshot/port/utils.ts +++ b/packages/vitest/src/integrations/snapshot/port/utils.ts @@ -161,17 +161,27 @@ export async function saveSnapshotFile( export function prepareExpected(expected?: string) { function findStartIndent() { - const match = /^( +)}\s+$/m.exec(expected || '') - return match?.[1]?.length || 0 + // Attemps to find indentation for objects. + // Matches the ending tag of the object. + const matchObject = /^( +)}\s+$/m.exec(expected || '') + const objectIndent = matchObject?.[1]?.length + + if (objectIndent) + return objectIndent + + // Attempts to find indentation for texts. + // Matches the quote of first line. + const matchText = /^\n( +)"/.exec(expected || '') + return matchText?.[1]?.length || 0 } - const startIdent = findStartIndent() + const startIndent = findStartIndent() let expectedTrimmed = expected?.trim() - if (startIdent) { + if (startIndent) { expectedTrimmed = expectedTrimmed - ?.replace(new RegExp(`^${' '.repeat(startIdent)}`, 'gm'), '').replace(/ +}$/, '}') + ?.replace(new RegExp(`^${' '.repeat(startIndent)}`, 'gm'), '').replace(/ +}$/, '}') } return expectedTrimmed diff --git a/test/core/test/snapshot-inline.test.ts b/test/core/test/snapshot-inline.test.ts index 5c357d9c37f7..4ce0aac94be6 100644 --- a/test/core/test/snapshot-inline.test.ts +++ b/test/core/test/snapshot-inline.test.ts @@ -67,6 +67,28 @@ test('throwing inline snapshots', () => { "error": "omega", } `) + + expect(() => { + // eslint-disable-next-line no-throw-literal + throw { some: { nested: { error: 'object' } } } + }).toThrowErrorMatchingInlineSnapshot(` + { + "some": { + "nested": { + "error": "object", + }, + }, + } + `) + + expect(() => { + throw ['Inline', 'snapshot', 'with', 'newlines'].join('\n') + }).toThrowErrorMatchingInlineSnapshot(` + "Inline + snapshot + with + newlines" + `) }) test('properties inline snapshot', () => {