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

fix(inline-snapshots): detect linebreaks #1232

Merged
merged 3 commits into from May 4, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 15 additions & 5 deletions packages/vitest/src/integrations/snapshot/port/utils.ts
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions test/core/test/snapshot-inline.test.ts
Expand Up @@ -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', () => {
Expand Down