Skip to content

Commit 97b1f9d

Browse files
authored
fix(prefer-snapshot-hint): support passing hint to toMatchSnapshot as first argument (#1070)
1 parent 33f38cc commit 97b1f9d

File tree

2 files changed

+58
-4
lines changed

2 files changed

+58
-4
lines changed

src/rules/__tests__/prefer-snapshot-hint.test.ts

+36
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,28 @@ ruleTester.run('prefer-snapshot-hint (always)', rule, {
2828
code: 'expect(1).toMatchSnapshot({}, "my snapshot");',
2929
options: ['always'],
3030
},
31+
{
32+
code: 'expect(1).toMatchSnapshot("my snapshot");',
33+
options: ['always'],
34+
},
35+
{
36+
code: 'expect(1).toMatchSnapshot(`my snapshot`);',
37+
options: ['always'],
38+
},
39+
{
40+
code: dedent`
41+
const x = {};
42+
expect(1).toMatchSnapshot(x, "my snapshot");
43+
`,
44+
options: ['always'],
45+
},
46+
{
47+
code: dedent`
48+
const x = "snapshot";
49+
expect(1).toMatchSnapshot(\`my $\{x}\`);
50+
`,
51+
options: ['always'],
52+
},
3153
{
3254
code: 'expect(1).toThrowErrorMatchingSnapshot("my snapshot");',
3355
options: ['always'],
@@ -64,6 +86,20 @@ ruleTester.run('prefer-snapshot-hint (always)', rule, {
6486
},
6587
],
6688
},
89+
{
90+
code: dedent`
91+
const x = "we can't know if this is a string or not";
92+
expect(1).toMatchSnapshot(x);
93+
`,
94+
options: ['always'],
95+
errors: [
96+
{
97+
messageId: 'missingHint',
98+
column: 11,
99+
line: 2,
100+
},
101+
],
102+
},
67103
{
68104
code: 'expect(1).toThrowErrorMatchingSnapshot();',
69105
options: ['always'],

src/rules/prefer-snapshot-hint.ts

+22-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
ParsedExpectMatcher,
33
createRule,
44
isExpectCall,
5+
isStringNode,
56
parseExpectCall,
67
} from './utils';
78

@@ -12,10 +13,27 @@ const isSnapshotMatcher = (matcher: ParsedExpectMatcher) => {
1213
};
1314

1415
const isSnapshotMatcherWithoutHint = (matcher: ParsedExpectMatcher) => {
15-
const expectedNumberOfArgumentsWithHint =
16-
1 + Number(matcher.name === 'toMatchSnapshot');
17-
18-
return matcher.arguments?.length !== expectedNumberOfArgumentsWithHint;
16+
if (!matcher.arguments || matcher.arguments.length === 0) {
17+
return true;
18+
}
19+
20+
// this matcher only supports one argument which is the hint
21+
if (matcher.name !== 'toMatchSnapshot') {
22+
return matcher.arguments.length !== 1;
23+
}
24+
25+
// if we're being passed two arguments,
26+
// the second one should be the hint
27+
if (matcher.arguments.length === 2) {
28+
return false;
29+
}
30+
31+
const [arg] = matcher.arguments;
32+
33+
// the first argument to `toMatchSnapshot` can be _either_ a snapshot hint or
34+
// an object with asymmetric matchers, so we can't just assume that the first
35+
// argument is a hint when it's by itself.
36+
return !isStringNode(arg);
1937
};
2038

2139
const messages = {

0 commit comments

Comments
 (0)