Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(prefer-snapshot-hint): support passing hint to toMatchSnapshot
…as first argument (#1070)
  • Loading branch information
G-Rath committed Mar 19, 2022
1 parent 33f38cc commit 97b1f9d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
36 changes: 36 additions & 0 deletions src/rules/__tests__/prefer-snapshot-hint.test.ts
Expand Up @@ -28,6 +28,28 @@ ruleTester.run('prefer-snapshot-hint (always)', rule, {
code: 'expect(1).toMatchSnapshot({}, "my snapshot");',
options: ['always'],
},
{
code: 'expect(1).toMatchSnapshot("my snapshot");',
options: ['always'],
},
{
code: 'expect(1).toMatchSnapshot(`my snapshot`);',
options: ['always'],
},
{
code: dedent`
const x = {};
expect(1).toMatchSnapshot(x, "my snapshot");
`,
options: ['always'],
},
{
code: dedent`
const x = "snapshot";
expect(1).toMatchSnapshot(\`my $\{x}\`);
`,
options: ['always'],
},
{
code: 'expect(1).toThrowErrorMatchingSnapshot("my snapshot");',
options: ['always'],
Expand Down Expand Up @@ -64,6 +86,20 @@ ruleTester.run('prefer-snapshot-hint (always)', rule, {
},
],
},
{
code: dedent`
const x = "we can't know if this is a string or not";
expect(1).toMatchSnapshot(x);
`,
options: ['always'],
errors: [
{
messageId: 'missingHint',
column: 11,
line: 2,
},
],
},
{
code: 'expect(1).toThrowErrorMatchingSnapshot();',
options: ['always'],
Expand Down
26 changes: 22 additions & 4 deletions src/rules/prefer-snapshot-hint.ts
Expand Up @@ -2,6 +2,7 @@ import {
ParsedExpectMatcher,
createRule,
isExpectCall,
isStringNode,
parseExpectCall,
} from './utils';

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

const isSnapshotMatcherWithoutHint = (matcher: ParsedExpectMatcher) => {
const expectedNumberOfArgumentsWithHint =
1 + Number(matcher.name === 'toMatchSnapshot');

return matcher.arguments?.length !== expectedNumberOfArgumentsWithHint;
if (!matcher.arguments || matcher.arguments.length === 0) {
return true;
}

// this matcher only supports one argument which is the hint
if (matcher.name !== 'toMatchSnapshot') {
return matcher.arguments.length !== 1;
}

// if we're being passed two arguments,
// the second one should be the hint
if (matcher.arguments.length === 2) {
return false;
}

const [arg] = matcher.arguments;

// the first argument to `toMatchSnapshot` can be _either_ a snapshot hint or
// an object with asymmetric matchers, so we can't just assume that the first
// argument is a hint when it's by itself.
return !isStringNode(arg);
};

const messages = {
Expand Down

0 comments on commit 97b1f9d

Please sign in to comment.