Skip to content

Commit 3037070

Browse files
committed
Throw error when duplicate snapshot name
1 parent 9fccf7d commit 3037070

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

e2e/__tests__/toMatchNamedSnapshot.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,28 @@ test('handles property matchers with deep properties', () => {
308308
}
309309
});
310310

311+
test('error duplicate snapshot name', () => {
312+
const filename = 'duplicate-match-named-snapshot.test.js';
313+
const template = makeTemplate(
314+
`test('duplicate named snapshots', () => {
315+
expect($1).toMatchNamedSnapshot('basic-support');
316+
expect($1).toMatchNamedSnapshot('basic-support');
317+
});
318+
`,
319+
);
320+
{
321+
writeFiles(TESTS_DIR, {[filename]: template(['test'])});
322+
const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]);
323+
console.log(stderr);
324+
325+
expect(stderr).toMatch(
326+
'The specific snapshot name was duplicate with the other snapshot.',
327+
);
328+
expect(stderr).toMatch('Snapshot name: basic-support');
329+
expect(exitCode).toBe(1);
330+
}
331+
});
332+
311333
test('support concurrent testing', () => {
312334
const filename = 'match-snapshot-when-test-concurrent.test.js';
313335
const template = makeTemplate(`describe('group 1', () => {

packages/jest-snapshot/src/index.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,12 @@ import type {
3636
MatchSnapshotConfig,
3737
SnapshotNameConfig,
3838
} from './types';
39-
import {deepMerge, escapeBacktickString, serialize} from './utils';
39+
import {
40+
deepMerge,
41+
escapeBacktickString,
42+
serialize,
43+
testNameToKey,
44+
} from './utils';
4045

4146
export {addSerializer, getSerializers} from './plugins';
4247
export {
@@ -439,7 +444,14 @@ const _toMatchSnapshot = (config: MatchSnapshotConfig) => {
439444
received,
440445
testName: fullTestName,
441446
});
442-
const {actual, count, expected, pass} = result;
447+
const {actual, count, expected, key, pass} = result;
448+
449+
if (snapshotName && key == testNameToKey(fullTestName, 1)) {
450+
throw new Error(
451+
'The specific snapshot name was duplicate with the other snapshot.\n\n' +
452+
`Snapshot name: ${snapshotName}`,
453+
);
454+
}
443455

444456
if (pass) {
445457
return {message: () => '', pass: true};

0 commit comments

Comments
 (0)