@vitest/snapshot
Advanced tools
Comparing version 2.0.0-beta.10 to 2.0.0-beta.11
@@ -1,2 +0,2 @@ | ||
import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment-BaTWxlGj.js'; | ||
import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment-Ddx0EDtY.js'; | ||
@@ -3,0 +3,0 @@ declare class NodeSnapshotEnvironment implements SnapshotEnvironment { |
@@ -19,6 +19,3 @@ import { promises, existsSync } from 'node:fs'; | ||
return join( | ||
join( | ||
dirname(filepath), | ||
this.options.snapshotsDirName ?? "__snapshots__" | ||
), | ||
join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), | ||
`${basename(filepath)}.snap` | ||
@@ -35,9 +32,11 @@ ); | ||
async readSnapshotFile(filepath) { | ||
if (!existsSync(filepath)) | ||
if (!existsSync(filepath)) { | ||
return null; | ||
} | ||
return promises.readFile(filepath, "utf-8"); | ||
} | ||
async removeSnapshotFile(filepath) { | ||
if (existsSync(filepath)) | ||
if (existsSync(filepath)) { | ||
await promises.unlink(filepath); | ||
} | ||
} | ||
@@ -44,0 +43,0 @@ } |
@@ -1,4 +0,4 @@ | ||
import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './index-CTmsp3V1.js'; | ||
export { c as SnapshotData, e as SnapshotSerializer, f as SnapshotSummary, d as SnapshotUpdateState, U as UncheckedSnapshot } from './index-CTmsp3V1.js'; | ||
import { S as SnapshotEnvironment } from './environment-BaTWxlGj.js'; | ||
import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './index-reKGmLsM.js'; | ||
export { c as SnapshotData, e as SnapshotSerializer, f as SnapshotSummary, d as SnapshotUpdateState, U as UncheckedSnapshot } from './index-reKGmLsM.js'; | ||
import { S as SnapshotEnvironment } from './environment-Ddx0EDtY.js'; | ||
import { Plugin, Plugins } from 'pretty-format'; | ||
@@ -5,0 +5,0 @@ |
@@ -89,15 +89,19 @@ import { plugins, format } from 'pretty-format'; | ||
if (isCharString && beforeChar !== "\\") { | ||
if (inString === char) | ||
if (inString === char) { | ||
inString = null; | ||
else if (!inString) | ||
} else if (!inString) { | ||
inString = char; | ||
} | ||
} | ||
if (!inString) { | ||
if (char === "(") | ||
if (char === "(") { | ||
startedBracers++; | ||
if (char === ")") | ||
} | ||
if (char === ")") { | ||
endedBracers++; | ||
} | ||
} | ||
if (startedBracers && endedBracers && startedBracers === endedBracers) | ||
if (startedBracers && endedBracers && startedBracers === endedBracers) { | ||
return charIndex; | ||
} | ||
} | ||
@@ -146,6 +150,8 @@ return null; | ||
let start = 0; | ||
if (lineNumber > lines.length) | ||
if (lineNumber > lines.length) { | ||
return source.length; | ||
for (let i = 0; i < lineNumber - 1; i++) | ||
} | ||
for (let i = 0; i < lineNumber - 1; i++) { | ||
start += lines[i].length + nl; | ||
} | ||
return start + columnNumber; | ||
@@ -165,4 +171,5 @@ } | ||
const lineLength = lines[line].length + nl; | ||
if (counted + lineLength >= offset) | ||
if (counted + lineLength >= offset) { | ||
break; | ||
} | ||
counted += lineLength; | ||
@@ -237,3 +244,15 @@ } | ||
const indentationNext = indentation + config.indent; | ||
callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`; | ||
callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer( | ||
val.mock.calls, | ||
config, | ||
indentationNext, | ||
depth, | ||
refs | ||
)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer( | ||
val.mock.results, | ||
config, | ||
indentationNext, | ||
depth, | ||
refs | ||
)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`; | ||
} | ||
@@ -273,4 +292,5 @@ return `[MockFunction${nameString}]${callsString}`; | ||
function keyToTestName(key) { | ||
if (!/ \d+$/.test(key)) | ||
if (!/ \d+$/.test(key)) { | ||
throw new Error("Snapshot keys must end with a number."); | ||
} | ||
return key.replace(/ \d+$/, ""); | ||
@@ -292,4 +312,5 @@ } | ||
const isInvalid = snapshotContents; | ||
if ((update === "all" || update === "new") && isInvalid) | ||
if ((update === "all" || update === "new") && isInvalid) { | ||
dirty = true; | ||
} | ||
return { data, dirty }; | ||
@@ -329,3 +350,5 @@ } | ||
const snapshots = Object.keys(snapshotData).sort(naturalCompare$1).map( | ||
(key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};` | ||
(key) => `exports[${printBacktickString(key)}] = ${printBacktickString( | ||
normalizeNewlines(snapshotData[key]) | ||
)};` | ||
); | ||
@@ -338,8 +361,6 @@ const content = `${environment.getHeader()} | ||
const skipWriting = oldContent != null && oldContent === content; | ||
if (skipWriting) | ||
if (skipWriting) { | ||
return; | ||
await environment.saveSnapshotFile( | ||
snapshotPath, | ||
content | ||
); | ||
} | ||
await environment.saveSnapshotFile(snapshotPath, content); | ||
} | ||
@@ -351,4 +372,5 @@ function prepareExpected(expected) { | ||
const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length; | ||
if (objectIndent) | ||
if (objectIndent) { | ||
return objectIndent; | ||
} | ||
const matchText = /^\n( +)"/.exec(expected || ""); | ||
@@ -383,5 +405,7 @@ return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0; | ||
if (isObject(source[key]) && !source[key].$$typeof) { | ||
if (!(key in target)) | ||
if (!(key in target)) { | ||
Object.assign(mergedOutput, { [key]: source[key] }); | ||
else mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); | ||
} else { | ||
mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); | ||
} | ||
} else if (Array.isArray(source[key])) { | ||
@@ -972,5 +996,3 @@ mergedOutput[key] = deepMergeArray(target[key], source[key]); | ||
// browser related deps | ||
"/deps/chai.js", | ||
"/deps/vitest___chai.js", | ||
"/deps/p-limit.js", | ||
"/deps/", | ||
/node:\w+/, | ||
@@ -982,11 +1004,14 @@ /__vitest_test__/, | ||
function extractLocation(urlLike) { | ||
if (!urlLike.includes(":")) | ||
if (!urlLike.includes(":")) { | ||
return [urlLike]; | ||
} | ||
const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; | ||
const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); | ||
if (!parts) | ||
if (!parts) { | ||
return [urlLike]; | ||
} | ||
let url = parts[1]; | ||
if (url.startsWith("async ")) | ||
if (url.startsWith("async ")) { | ||
url = url.slice(6); | ||
} | ||
if (url.startsWith("http:") || url.startsWith("https:")) { | ||
@@ -1004,14 +1029,23 @@ const urlObj = new URL(url); | ||
let line = raw.trim(); | ||
if (SAFARI_NATIVE_CODE_REGEXP.test(line)) | ||
if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { | ||
return null; | ||
if (line.includes(" > eval")) | ||
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); | ||
if (!line.includes("@") && !line.includes(":")) | ||
} | ||
if (line.includes(" > eval")) { | ||
line = line.replace( | ||
/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, | ||
":$1" | ||
); | ||
} | ||
if (!line.includes("@") && !line.includes(":")) { | ||
return null; | ||
} | ||
const functionNameRegex = /((.*".+"[^@]*)?[^@]*)(@)/; | ||
const matches = line.match(functionNameRegex); | ||
const functionName = matches && matches[1] ? matches[1] : void 0; | ||
const [url, lineNumber, columnNumber] = extractLocation(line.replace(functionNameRegex, "")); | ||
if (!url || !lineNumber || !columnNumber) | ||
const [url, lineNumber, columnNumber] = extractLocation( | ||
line.replace(functionNameRegex, "") | ||
); | ||
if (!url || !lineNumber || !columnNumber) { | ||
return null; | ||
} | ||
return { | ||
@@ -1026,21 +1060,29 @@ file: url, | ||
let line = raw.trim(); | ||
if (!CHROME_IE_STACK_REGEXP.test(line)) | ||
if (!CHROME_IE_STACK_REGEXP.test(line)) { | ||
return null; | ||
if (line.includes("(eval ")) | ||
} | ||
if (line.includes("(eval ")) { | ||
line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); | ||
} | ||
let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); | ||
const location = sanitizedLine.match(/ (\(.+\)$)/); | ||
sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; | ||
const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); | ||
const [url, lineNumber, columnNumber] = extractLocation( | ||
location ? location[1] : sanitizedLine | ||
); | ||
let method = location && sanitizedLine || ""; | ||
let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url; | ||
if (!file || !lineNumber || !columnNumber) | ||
if (!file || !lineNumber || !columnNumber) { | ||
return null; | ||
if (method.startsWith("async ")) | ||
} | ||
if (method.startsWith("async ")) { | ||
method = method.slice(6); | ||
if (file.startsWith("file://")) | ||
} | ||
if (file.startsWith("file://")) { | ||
file = file.slice(7); | ||
} | ||
file = resolve$2(file); | ||
if (method) | ||
if (method) { | ||
method = method.replace(/__vite_ssr_import_\d+__\./g, ""); | ||
} | ||
return { | ||
@@ -1056,13 +1098,18 @@ method, | ||
let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); | ||
if (ignoreStackEntries.length) | ||
stacks = stacks.filter((stack2) => !ignoreStackEntries.some((p) => stack2.file.match(p))); | ||
if (ignoreStackEntries.length) { | ||
stacks = stacks.filter( | ||
(stack2) => !ignoreStackEntries.some((p) => stack2.file.match(p)) | ||
); | ||
} | ||
return stacks.map((stack2) => { | ||
var _a; | ||
const map = (_a = options.getSourceMap) == null ? void 0 : _a.call(options, stack2.file); | ||
if (!map || typeof map !== "object" || !map.version) | ||
if (!map || typeof map !== "object" || !map.version) { | ||
return stack2; | ||
} | ||
const traceMap = new TraceMap(map); | ||
const { line, column } = originalPositionFor(traceMap, stack2); | ||
if (line != null && column != null) | ||
if (line != null && column != null) { | ||
return { ...stack2, line, column }; | ||
} | ||
return stack2; | ||
@@ -1078,10 +1125,15 @@ }); | ||
function parseErrorStacktrace(e, options = {}) { | ||
if (!e || isPrimitive(e)) | ||
if (!e || isPrimitive(e)) { | ||
return []; | ||
if (e.stacks) | ||
} | ||
if (e.stacks) { | ||
return e.stacks; | ||
} | ||
const stackStr = e.stack || e.stackStr || ""; | ||
let stackFrames = parseStacktrace(stackStr, options); | ||
if (options.frameFilter) | ||
stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); | ||
if (options.frameFilter) { | ||
stackFrames = stackFrames.filter( | ||
(f) => options.frameFilter(e, f) !== false | ||
); | ||
} | ||
e.stacks = stackFrames; | ||
@@ -1094,14 +1146,17 @@ return stackFrames; | ||
const files = new Set(snapshots.map((i) => i.file)); | ||
await Promise.all(Array.from(files).map(async (file) => { | ||
const snaps = snapshots.filter((i) => i.file === file); | ||
const code = await environment.readSnapshotFile(file); | ||
const s = new MagicString(code); | ||
for (const snap of snaps) { | ||
const index = positionToOffset(code, snap.line, snap.column); | ||
replaceInlineSnap(code, s, index, snap.snapshot); | ||
} | ||
const transformed = s.toString(); | ||
if (transformed !== code) | ||
await environment.saveSnapshotFile(file, transformed); | ||
})); | ||
await Promise.all( | ||
Array.from(files).map(async (file) => { | ||
const snaps = snapshots.filter((i) => i.file === file); | ||
const code = await environment.readSnapshotFile(file); | ||
const s = new MagicString(code); | ||
for (const snap of snaps) { | ||
const index = positionToOffset(code, snap.line, snap.column); | ||
replaceInlineSnap(code, s, index, snap.snapshot); | ||
} | ||
const transformed = s.toString(); | ||
if (transformed !== code) { | ||
await environment.saveSnapshotFile(file, transformed); | ||
} | ||
}) | ||
); | ||
} | ||
@@ -1112,8 +1167,10 @@ const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/; | ||
const startMatch = startObjectRegex.exec(_code); | ||
if (!startMatch) | ||
if (!startMatch) { | ||
return false; | ||
} | ||
_code = _code.slice(startMatch.index); | ||
let callEnd = getCallLastIndex(_code); | ||
if (callEnd === null) | ||
if (callEnd === null) { | ||
return false; | ||
} | ||
callEnd += index + startMatch.index; | ||
@@ -1135,6 +1192,7 @@ const shapeStart = index + startMatch.index + startMatch[0].length; | ||
const s = code[index++]; | ||
if (s === "{") | ||
if (s === "{") { | ||
startBraces++; | ||
else if (s === "}") | ||
} else if (s === "}") { | ||
endBraces++; | ||
} | ||
} | ||
@@ -1151,4 +1209,5 @@ return index; | ||
const quote = "`"; | ||
if (isOneline) | ||
if (isOneline) { | ||
return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`; | ||
} | ||
return `${quote} | ||
@@ -1158,9 +1217,34 @@ ${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")} | ||
} | ||
const toMatchInlineName = "toMatchInlineSnapshot"; | ||
const toThrowErrorMatchingInlineName = "toThrowErrorMatchingInlineSnapshot"; | ||
function getCodeStartingAtIndex(code, index) { | ||
const indexInline = index - toMatchInlineName.length; | ||
if (code.slice(indexInline, index) === toMatchInlineName) { | ||
return { | ||
code: code.slice(indexInline), | ||
index: indexInline | ||
}; | ||
} | ||
const indexThrowInline = index - toThrowErrorMatchingInlineName.length; | ||
if (code.slice(index - indexThrowInline, index) === toThrowErrorMatchingInlineName) { | ||
return { | ||
code: code.slice(index - indexThrowInline), | ||
index: index - indexThrowInline | ||
}; | ||
} | ||
return { | ||
code: code.slice(index), | ||
index | ||
}; | ||
} | ||
const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/; | ||
function replaceInlineSnap(code, s, index, newSnap) { | ||
const codeStartingAtIndex = code.slice(index); | ||
function replaceInlineSnap(code, s, currentIndex, newSnap) { | ||
const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex); | ||
const startMatch = startRegex.exec(codeStartingAtIndex); | ||
const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex); | ||
if (!startMatch || startMatch.index !== (firstKeywordMatch == null ? void 0 : firstKeywordMatch.index)) | ||
const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec( | ||
codeStartingAtIndex | ||
); | ||
if (!startMatch || startMatch.index !== (firstKeywordMatch == null ? void 0 : firstKeywordMatch.index)) { | ||
return replaceObjectSnap(code, s, index, newSnap); | ||
} | ||
const quote = startMatch[1]; | ||
@@ -1175,4 +1259,5 @@ const startIndex = index + startMatch.index + startMatch[0].length; | ||
const endMatch = quoteEndRE.exec(code.slice(startIndex)); | ||
if (!endMatch) | ||
if (!endMatch) { | ||
return false; | ||
} | ||
const endIndex = startIndex + endMatch.index + endMatch[0].length; | ||
@@ -1210,6 +1295,9 @@ s.overwrite(startIndex - 1, endIndex, snapString); | ||
async function saveRawSnapshots(environment, snapshots) { | ||
await Promise.all(snapshots.map(async (snap) => { | ||
if (!snap.readonly) | ||
await environment.saveSnapshotFile(snap.file, snap.snapshot); | ||
})); | ||
await Promise.all( | ||
snapshots.map(async (snap) => { | ||
if (!snap.readonly) { | ||
await environment.saveSnapshotFile(snap.file, snap.snapshot); | ||
} | ||
}) | ||
); | ||
} | ||
@@ -1221,6 +1309,3 @@ | ||
this.snapshotPath = snapshotPath; | ||
const { data, dirty } = getSnapshotData( | ||
snapshotContent, | ||
options | ||
); | ||
const { data, dirty } = getSnapshotData(snapshotContent, options); | ||
this._fileExists = snapshotContent != null; | ||
@@ -1264,4 +1349,8 @@ this._initialData = data; | ||
static async create(testFilePath, options) { | ||
const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath); | ||
const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath); | ||
const snapshotPath = await options.snapshotEnvironment.resolvePath( | ||
testFilePath | ||
); | ||
const content = await options.snapshotEnvironment.readSnapshotFile( | ||
snapshotPath | ||
); | ||
return new SnapshotState(testFilePath, snapshotPath, content, options); | ||
@@ -1274,24 +1363,38 @@ } | ||
this._uncheckedKeys.forEach((uncheckedKey) => { | ||
if (keyToTestName(uncheckedKey) === testName) | ||
if (keyToTestName(uncheckedKey) === testName) { | ||
this._uncheckedKeys.delete(uncheckedKey); | ||
} | ||
}); | ||
} | ||
_inferInlineSnapshotStack(stacks) { | ||
const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); | ||
if (promiseIndex !== -1) | ||
const promiseIndex = stacks.findIndex( | ||
(i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/) | ||
); | ||
if (promiseIndex !== -1) { | ||
return stacks[promiseIndex + 3]; | ||
const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__")); | ||
} | ||
const stackIndex = stacks.findIndex( | ||
(i) => i.method.includes("__INLINE_SNAPSHOT__") | ||
); | ||
return stackIndex !== -1 ? stacks[stackIndex + 2] : null; | ||
} | ||
_addSnapshot(key, receivedSerialized, options) { | ||
var _a, _b; | ||
this._dirty = true; | ||
if (options.isInline) { | ||
const stacks = parseErrorStacktrace(options.error || new Error("snapshot"), { ignoreStackEntries: [] }); | ||
const stack = this._inferInlineSnapshotStack(stacks); | ||
if (!stack) { | ||
const error = options.error || new Error("snapshot"); | ||
const stacks = parseErrorStacktrace( | ||
error, | ||
{ ignoreStackEntries: [] } | ||
); | ||
const _stack = this._inferInlineSnapshotStack(stacks); | ||
if (!_stack) { | ||
throw new Error( | ||
`@vitest/snapshot: Couldn't infer stack frame for inline snapshot. | ||
${JSON.stringify(stacks)}` | ||
${JSON.stringify( | ||
stacks | ||
)}` | ||
); | ||
} | ||
const stack = ((_b = (_a = this.environment).processStackTrace) == null ? void 0 : _b.call(_a, _stack)) || _stack; | ||
stack.column--; | ||
@@ -1331,9 +1434,15 @@ this._inlineSnapshots.push({ | ||
if (hasExternalSnapshots) { | ||
await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath); | ||
await saveSnapshotFile( | ||
this._environment, | ||
this._snapshotData, | ||
this.snapshotPath | ||
); | ||
this._fileExists = true; | ||
} | ||
if (hasInlineSnapshots) | ||
if (hasInlineSnapshots) { | ||
await saveInlineSnapshots(this._environment, this._inlineSnapshots); | ||
if (hasRawSnapshots) | ||
} | ||
if (hasRawSnapshots) { | ||
await saveRawSnapshots(this._environment, this._rawSnapshots); | ||
} | ||
status.saved = true; | ||
@@ -1373,12 +1482,16 @@ } else if (!hasExternalSnapshots && this._fileExists) { | ||
const count = Number(this._counters.get(testName)); | ||
if (!key) | ||
if (!key) { | ||
key = testNameToKey(testName, count); | ||
if (!(isInline && this._snapshotData[key] !== void 0)) | ||
} | ||
if (!(isInline && this._snapshotData[key] !== void 0)) { | ||
this._uncheckedKeys.delete(key); | ||
} | ||
let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, void 0, this._snapshotFormat); | ||
if (!rawSnapshot) | ||
if (!rawSnapshot) { | ||
receivedSerialized = addExtraLineBreaks(receivedSerialized); | ||
} | ||
if (rawSnapshot) { | ||
if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) | ||
if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) { | ||
rawSnapshot.content = normalizeNewlines(rawSnapshot.content); | ||
} | ||
} | ||
@@ -1396,7 +1509,12 @@ const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key]; | ||
if (!pass) { | ||
if (hasSnapshot) | ||
if (hasSnapshot) { | ||
this.updated++; | ||
else | ||
} else { | ||
this.added++; | ||
this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); | ||
} | ||
this._addSnapshot(key, receivedSerialized, { | ||
error, | ||
isInline, | ||
rawSnapshot | ||
}); | ||
} else { | ||
@@ -1406,3 +1524,7 @@ this.matched++; | ||
} else { | ||
this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); | ||
this._addSnapshot(key, receivedSerialized, { | ||
error, | ||
isInline, | ||
rawSnapshot | ||
}); | ||
this.added++; | ||
@@ -1452,4 +1574,5 @@ } | ||
const uncheckedKeys = this.getUncheckedKeys(); | ||
if (uncheckedCount) | ||
if (uncheckedCount) { | ||
this.removeUncheckedKeys(); | ||
} | ||
const status = await this.save(); | ||
@@ -1501,6 +1624,3 @@ snapshot.fileDeleted = status.deleted; | ||
filepath, | ||
await SnapshotState.create( | ||
filepath, | ||
options | ||
) | ||
await SnapshotState.create(filepath, options) | ||
); | ||
@@ -1536,13 +1656,23 @@ } | ||
let { received } = options; | ||
if (!filepath) | ||
if (!filepath) { | ||
throw new Error("Snapshot cannot be used outside of test"); | ||
} | ||
if (typeof properties === "object") { | ||
if (typeof received !== "object" || !received) | ||
throw new Error("Received value must be an object when the matcher has properties"); | ||
if (typeof received !== "object" || !received) { | ||
throw new Error( | ||
"Received value must be an object when the matcher has properties" | ||
); | ||
} | ||
try { | ||
const pass2 = ((_b = (_a = this.options).isEqual) == null ? void 0 : _b.call(_a, received, properties)) ?? false; | ||
if (!pass2) | ||
throw createMismatchError("Snapshot properties mismatched", (_c = this.snapshotState) == null ? void 0 : _c.expand, received, properties); | ||
else | ||
if (!pass2) { | ||
throw createMismatchError( | ||
"Snapshot properties mismatched", | ||
(_c = this.snapshotState) == null ? void 0 : _c.expand, | ||
received, | ||
properties | ||
); | ||
} else { | ||
received = deepMergeSnapshot(received, properties); | ||
} | ||
} catch (err) { | ||
@@ -1553,6 +1683,3 @@ err.message = errorMessage || "Snapshot mismatched"; | ||
} | ||
const testName = [ | ||
name, | ||
...message ? [message] : [] | ||
].join(" > "); | ||
const testName = [name, ...message ? [message] : []].join(" > "); | ||
const snapshotState = this.getSnapshotState(filepath); | ||
@@ -1567,19 +1694,27 @@ const { actual, expected, key, pass } = snapshotState.match({ | ||
}); | ||
if (!pass) | ||
throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, (_d = this.snapshotState) == null ? void 0 : _d.expand, actual == null ? void 0 : actual.trim(), expected == null ? void 0 : expected.trim()); | ||
if (!pass) { | ||
throw createMismatchError( | ||
`Snapshot \`${key || "unknown"}\` mismatched`, | ||
(_d = this.snapshotState) == null ? void 0 : _d.expand, | ||
actual == null ? void 0 : actual.trim(), | ||
expected == null ? void 0 : expected.trim() | ||
); | ||
} | ||
} | ||
async assertRaw(options) { | ||
if (!options.rawSnapshot) | ||
if (!options.rawSnapshot) { | ||
throw new Error("Raw snapshot is required"); | ||
const { | ||
filepath = this.filepath, | ||
rawSnapshot | ||
} = options; | ||
} | ||
const { filepath = this.filepath, rawSnapshot } = options; | ||
if (rawSnapshot.content == null) { | ||
if (!filepath) | ||
if (!filepath) { | ||
throw new Error("Snapshot cannot be used outside of test"); | ||
} | ||
const snapshotState = this.getSnapshotState(filepath); | ||
options.filepath || (options.filepath = filepath); | ||
rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); | ||
rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) || void 0; | ||
rawSnapshot.file = await snapshotState.environment.resolveRawPath( | ||
filepath, | ||
rawSnapshot.file | ||
); | ||
rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? void 0; | ||
} | ||
@@ -1589,4 +1724,5 @@ return this.assert(options); | ||
async finishCurrentRun() { | ||
if (!this.snapshotState) | ||
if (!this.snapshotState) { | ||
return null; | ||
} | ||
const result = await this.snapshotState.pack(); | ||
@@ -1593,0 +1729,0 @@ this.snapshotState = void 0; |
@@ -1,4 +0,4 @@ | ||
import { S as SnapshotStateOptions, f as SnapshotSummary, b as SnapshotResult } from './index-CTmsp3V1.js'; | ||
import { S as SnapshotStateOptions, f as SnapshotSummary, b as SnapshotResult } from './index-reKGmLsM.js'; | ||
import 'pretty-format'; | ||
import './environment-BaTWxlGj.js'; | ||
import './environment-Ddx0EDtY.js'; | ||
@@ -5,0 +5,0 @@ declare class SnapshotManager { |
@@ -19,6 +19,3 @@ import { join, dirname, basename, isAbsolute, resolve } from 'pathe'; | ||
return join( | ||
join( | ||
dirname(testPath), | ||
"__snapshots__" | ||
), | ||
join(dirname(testPath), "__snapshots__"), | ||
`${basename(testPath)}${this.extension}` | ||
@@ -54,10 +51,14 @@ ); | ||
function addSnapshotResult(summary, result) { | ||
if (result.added) | ||
if (result.added) { | ||
summary.filesAdded++; | ||
if (result.fileDeleted) | ||
} | ||
if (result.fileDeleted) { | ||
summary.filesRemoved++; | ||
if (result.unmatched) | ||
} | ||
if (result.unmatched) { | ||
summary.filesUnmatched++; | ||
if (result.updated) | ||
} | ||
if (result.updated) { | ||
summary.filesUpdated++; | ||
} | ||
summary.added += result.added; | ||
@@ -64,0 +65,0 @@ summary.matched += result.matched; |
{ | ||
"name": "@vitest/snapshot", | ||
"type": "module", | ||
"version": "2.0.0-beta.10", | ||
"version": "2.0.0-beta.11", | ||
"description": "Vitest snapshot manager", | ||
@@ -48,3 +48,3 @@ "license": "MIT", | ||
"natural-compare": "^1.4.0", | ||
"@vitest/utils": "2.0.0-beta.10" | ||
"@vitest/utils": "2.0.0-beta.11" | ||
}, | ||
@@ -51,0 +51,0 @@ "scripts": { |
@@ -15,3 +15,4 @@ # @vitest/snapshot | ||
// this function is called when `.toMatchSnapshot({ property: 1 })` is called | ||
isEqual: (received, expected) => equals(received, expected, [iterableEquality, subsetEquality]), | ||
isEqual: (received, expected) => | ||
equals(received, expected, [iterableEquality, subsetEquality]), | ||
}) | ||
@@ -57,3 +58,7 @@ | ||
await client.startCurrentRun(getCurrentFilepath(), getCurrentTestName(), options) | ||
await client.startCurrentRun( | ||
getCurrentFilepath(), | ||
getCurrentTestName(), | ||
options | ||
) | ||
@@ -60,0 +65,0 @@ // this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
69169
1990
85