Skip to content

Commit

Permalink
Throw error when duplicate snapshot name
Browse files Browse the repository at this point in the history
  • Loading branch information
bakamitai456 committed Jun 15, 2023
1 parent 9fccf7d commit 3037070
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
22 changes: 22 additions & 0 deletions e2e/__tests__/toMatchNamedSnapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,28 @@ test('handles property matchers with deep properties', () => {
}
});

test('error duplicate snapshot name', () => {
const filename = 'duplicate-match-named-snapshot.test.js';
const template = makeTemplate(
`test('duplicate named snapshots', () => {
expect($1).toMatchNamedSnapshot('basic-support');
expect($1).toMatchNamedSnapshot('basic-support');
});
`,
);
{
writeFiles(TESTS_DIR, {[filename]: template(['test'])});
const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false', filename]);
console.log(stderr);

expect(stderr).toMatch(
'The specific snapshot name was duplicate with the other snapshot.',
);
expect(stderr).toMatch('Snapshot name: basic-support');
expect(exitCode).toBe(1);
}
});

test('support concurrent testing', () => {
const filename = 'match-snapshot-when-test-concurrent.test.js';
const template = makeTemplate(`describe('group 1', () => {
Expand Down
16 changes: 14 additions & 2 deletions packages/jest-snapshot/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ import type {
MatchSnapshotConfig,
SnapshotNameConfig,
} from './types';
import {deepMerge, escapeBacktickString, serialize} from './utils';
import {
deepMerge,
escapeBacktickString,
serialize,
testNameToKey,
} from './utils';

export {addSerializer, getSerializers} from './plugins';
export {
Expand Down Expand Up @@ -439,7 +444,14 @@ const _toMatchSnapshot = (config: MatchSnapshotConfig) => {
received,
testName: fullTestName,
});
const {actual, count, expected, pass} = result;
const {actual, count, expected, key, pass} = result;

if (snapshotName && key == testNameToKey(fullTestName, 1)) {
throw new Error(
'The specific snapshot name was duplicate with the other snapshot.\n\n' +
`Snapshot name: ${snapshotName}`,
);
}

if (pass) {
return {message: () => '', pass: true};
Expand Down

0 comments on commit 3037070

Please sign in to comment.