Skip to content

Commit

Permalink
fix(inline-snapshots): detect linebreaks (#1232)
Browse files Browse the repository at this point in the history
* style: fix typo

* test(inline-snapshot): add test for nested object

* fix(inline-snapshots): detect linebreaks
  • Loading branch information
AriPerkkio committed May 4, 2022
1 parent 1c7c733 commit 4de5da7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
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

0 comments on commit 4de5da7

Please sign in to comment.