Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(prefer-snapshot-hint): support passing hint to toMatchSnapshot as first argument #1070

Merged
merged 1 commit into from Mar 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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