Skip to content

Commit

Permalink
fix: snapshot ignores indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Jan 8, 2022
1 parent 4603ffd commit aff1481
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 24 deletions.
5 changes: 3 additions & 2 deletions packages/vitest/package.json
Expand Up @@ -74,6 +74,7 @@
"cac": "^6.7.12",
"chai-subset": "^1.6.0",
"cli-truncate": "^3.1.0",
"detect-indent": "^7.0.0",
"diff": "^5.0.0",
"execa": "^6.0.0",
"fast-glob": "^3.2.8",
Expand All @@ -99,10 +100,10 @@
"ws": "^8.4.0"
},
"peerDependencies": {
"@vitest/ui": "*",
"c8": "*",
"happy-dom": "*",
"jsdom": "*",
"@vitest/ui": "*"
"jsdom": "*"
},
"peerDependenciesMeta": {
"c8": {
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/snapshot/client.ts
Expand Up @@ -72,7 +72,7 @@ export class SnapshotClient {
testName,
received,
isInline,
inlineSnapshot: inlineSnapshot?.trim(),
inlineSnapshot,
})

if (!pass) {
Expand Down
@@ -1,5 +1,6 @@
import { promises as fs } from 'fs'
import type MagicString from 'magic-string'
import detectIndent from 'detect-indent'
import { rpc } from '../../../runtime/rpc'
import { getOriginalPos, posToNumber } from '../../../utils/source-map'

Expand All @@ -24,7 +25,8 @@ export async function saveInlineSnapshots(
for (const snap of snaps) {
const pos = await getOriginalPos(map, snap)
const index = posToNumber(code, pos!)
replaceInlineSnap(code, s, index, snap.snapshot) // TODO: support indent: ' '.repeat(4))
const { indent } = detectIndent(code.slice(index - pos!.column))
replaceInlineSnap(code, s, index, snap.snapshot, indent + indent)
}

const transformed = s.toString()
Expand Down Expand Up @@ -88,7 +90,7 @@ function prepareSnapString(snap: string, indent: string) {
const isOneline = !snap.includes('\n')
return isOneline
? `'${snap.replace(/'/g, '\\\'').trim()}'`
: `\`${snap.replace(/`/g, '\\`').trimEnd()}\``
: `\`${snap.replace(/`/g, '\\`').trimEnd()}\n${indent}\``
}

const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(['"`\)])/m
Expand Down
10 changes: 6 additions & 4 deletions packages/vitest/src/integrations/snapshot/port/state.ts
Expand Up @@ -19,6 +19,7 @@ import {
addExtraLineBreaks,
getSnapshotData,
keyToTestName,
prepareExpected,
removeExtraLineBreaks,
saveSnapshotFile,
serialize,
Expand Down Expand Up @@ -188,7 +189,8 @@ export default class SnapshotState {

const receivedSerialized = addExtraLineBreaks(serialize(received, undefined, this._snapshotFormat))
const expected = isInline ? inlineSnapshot : this._snapshotData[key]
const pass = expected?.trim() === receivedSerialized?.trim()
const expectedTrimmed = prepareExpected(expected)
const pass = expectedTrimmed === receivedSerialized?.trim()
const hasSnapshot = expected !== undefined
const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath)

Expand Down Expand Up @@ -247,9 +249,9 @@ export default class SnapshotState {
actual: removeExtraLineBreaks(receivedSerialized),
count,
expected:
expected !== undefined
? removeExtraLineBreaks(expected)
: undefined,
expectedTrimmed !== undefined
? removeExtraLineBreaks(expectedTrimmed)
: undefined,
key,
pass: false,
}
Expand Down
18 changes: 18 additions & 0 deletions packages/vitest/src/integrations/snapshot/port/utils.ts
Expand Up @@ -157,3 +157,21 @@ export async function saveSnapshotFile(
'utf-8',
)
}

export function prepareExpected(expected?: string) {
function findStartIndent() {
const match = /^( +)}\s+$/m.exec(expected || '')
return match?.[1]?.length || 0
}

const startIdent = findStartIndent()

let expectedTrimmed = expected?.trim()

if (startIdent) {
expectedTrimmed = expectedTrimmed
?.replaceAll(new RegExp(`^${' '.repeat(startIdent)}`, 'gm'), '').replace(/ +}$/, '}')
}

return expectedTrimmed
}
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion test/core/test/inline-snap.test.ts
Expand Up @@ -17,7 +17,8 @@ expect('foo').toMatchInlineSnapshot(\`{
"
expect('foo').toMatchInlineSnapshot('\\"bar\\"')
expect('foo').toMatchInlineSnapshot(\`\\"bar
foo\\"\`)
foo\\"
\`)
"`)
})
})
31 changes: 17 additions & 14 deletions test/core/test/snapshot.test.ts
Expand Up @@ -9,12 +9,13 @@ test('snapshot', () => {
test('inline snapshot', () => {
expect('inline string').toMatchInlineSnapshot('"inline string"')
expect({ foo: { type: 'object', map: new Map() } }).toMatchInlineSnapshot(`
{
"foo": {
"map": Map {},
"type": "object",
},
}`)
{
"foo": {
"map": Map {},
"type": "object",
},
}
`)
})

test('snapshot with big array', () => {
Expand Down Expand Up @@ -59,9 +60,10 @@ test('throwing inline snapshots', () => {
// eslint-disable-next-line no-throw-literal
throw { error: 'omega' }
}).toThrowErrorMatchingInlineSnapshot(`
{
"error": "omega",
}`)
{
"error": "omega",
}
`)
})

test('properties snapshot', () => {
Expand Down Expand Up @@ -102,9 +104,10 @@ test('properties inline snapshot', () => {
createdAt: expect.any(Date),
id: expect.any(Number),
}, `
{
"createdAt": Any<Date>,
"id": Any<Number>,
"name": "LeBron James",
}`)
{
"createdAt": Any<Date>,
"id": Any<Number>,
"name": "LeBron James",
}
`)
})

0 comments on commit aff1481

Please sign in to comment.