@@ -34,21 +34,47 @@ export async function saveInlineSnapshots(
3434const startObjectRegex = / (?: t o M a t c h I n l i n e S n a p s h o t | t o T h r o w E r r o r M a t c h i n g I n l i n e S n a p s h o t ) \s * \( \s * (?: \/ \* [ \S \s ] * \* \/ \s * | \/ \/ .* \s + ) * \s * ( { ) / m
3535
3636function replaceObjectSnap ( code : string , s : MagicString , index : number , newSnap : string ) {
37- code = code . slice ( index )
38- const startMatch = startObjectRegex . exec ( code )
37+ let _code = code . slice ( index )
38+ const startMatch = startObjectRegex . exec ( _code )
3939 if ( ! startMatch )
4040 return false
4141
42- code = code . slice ( startMatch . index )
43- const charIndex = getCallLastIndex ( code )
44- if ( charIndex === null )
42+ _code = _code . slice ( startMatch . index )
43+
44+ let callEnd = getCallLastIndex ( _code )
45+ if ( callEnd === null )
4546 return false
47+ callEnd += index + startMatch . index
48+
49+ const shapeStart = index + startMatch . index + startMatch [ 0 ] . length
50+ const shapeEnd = getObjectShapeEndIndex ( code , shapeStart )
51+ const snap = `, ${ prepareSnapString ( newSnap , code , index ) } `
4652
47- s . appendLeft ( index + startMatch . index + charIndex , `, ${ prepareSnapString ( newSnap , code , index ) } ` )
53+ if ( shapeEnd === callEnd ) {
54+ // toMatchInlineSnapshot({ foo: expect.any(String) })
55+ s . appendLeft ( callEnd , snap )
56+ }
57+ else {
58+ // toMatchInlineSnapshot({ foo: expect.any(String) }, ``)
59+ s . overwrite ( shapeEnd , callEnd , snap )
60+ }
4861
4962 return true
5063}
5164
65+ function getObjectShapeEndIndex ( code : string , index : number ) {
66+ let startBraces = 1
67+ let endBraces = 0
68+ while ( startBraces !== endBraces && index < code . length ) {
69+ const s = code [ index ++ ]
70+ if ( s === '{' )
71+ startBraces ++
72+ else if ( s === '}' )
73+ endBraces ++
74+ }
75+ return index
76+ }
77+
5278function prepareSnapString ( snap : string , source : string , index : number ) {
5379 const lineNumber = offsetToLineNumber ( source , index )
5480 const line = source . split ( lineSplitRE ) [ lineNumber - 1 ]
0 commit comments