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

feat/interpolation #79

Merged
merged 1 commit into from
Mar 1, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 23 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,28 +74,29 @@ To use the all configuration, extend it in your `.eslintrc` file:
🔧 Automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/user-guide/command-line-interface#--fix).\
💡 Manually fixable by [editor suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).

| Name                     | Description | ⚠️ | 🔧 | 💡 |
| :----------------------------------------------------------------- | :----------------------------------------------------------------------- | :- | :- | :- |
| [consistent-test-filename](docs/rules/consistent-test-filename.md) | forbidden .spec test file pattern | 🌐 | | |
| [consistent-test-it](docs/rules/consistent-test-it.md) | Prefer test or it but not both | 🌐 | 🔧 | |
| [expect-expect](docs/rules/expect-expect.md) | Enforce having expectation in test body | ✅ | | |
| [max-expects](docs/rules/max-expects.md) | Enforce a maximum number of expect per test | 🌐 | | |
| [max-nested-describe](docs/rules/max-nested-describe.md) | Nested describe block should be less than set max value or default value | 🌐 | | |
| [no-alias-methods](docs/rules/no-alias-methods.md) | Disallow alias methods | 🌐 | 🔧 | |
| [no-commented-out-tests](docs/rules/no-commented-out-tests.md) | Disallow commented out tests | ✅ | | |
| [no-conditional-expect](docs/rules/no-conditional-expect.md) | Disallow conditional expects | 🌐 | | |
| [no-conditional-in-test](docs/rules/no-conditional-in-test.md) | Disallow conditional tests | 🌐 | | |
| [no-conditional-tests](docs/rules/no-conditional-tests.md) | Disallow conditional tests | 🌐 | | |
| [no-disabled-tests](docs/rules/no-disabled-tests.md) | Disallow disabled tests | 🌐 | | |
| [no-done-callback](docs/rules/no-done-callback.md) | Disallow using a callback in asynchrounous tests and hooks | 🌐 | | 💡 |
| [no-duplicate-hooks](docs/rules/no-duplicate-hooks.md) | Disallow duplicate hooks and teardown hooks | 🌐 | | |
| [no-focused-tests](docs/rules/no-focused-tests.md) | Disallow focused tests | 🌐 | 🔧 | |
| [no-hooks](docs/rules/no-hooks.md) | Disallow setup and teardown hooks | 🌐 | | |
| [no-identical-title](docs/rules/no-identical-title.md) | Disallow identical titles | ✅ | 🔧 | |
| [no-restricted-vi-methods](docs/rules/no-restricted-vi-methods.md) | Disallow specific `vi.` methods | 🌐 | | |
| [no-skipped-tests](docs/rules/no-skipped-tests.md) | Disallow skipped tests | 🌐 | | |
| [prefer-lowercase-title](docs/rules/prefer-lowercase-title.md) | Enforce lowercase titles | 🌐 | 🔧 | |
| [prefer-to-be](docs/rules/prefer-to-be.md) | Suggest using toBe() | ✅ | 🔧 | |
| Name                          | Description | ⚠️ | 🔧 | 💡 |
| :--------------------------------------------------------------------------- | :----------------------------------------------------------------------- | :- | :- | :- |
| [consistent-test-filename](docs/rules/consistent-test-filename.md) | forbidden .spec test file pattern | 🌐 | | |
| [consistent-test-it](docs/rules/consistent-test-it.md) | Prefer test or it but not both | 🌐 | 🔧 | |
| [expect-expect](docs/rules/expect-expect.md) | Enforce having expectation in test body | ✅ | | |
| [max-expects](docs/rules/max-expects.md) | Enforce a maximum number of expect per test | 🌐 | | |
| [max-nested-describe](docs/rules/max-nested-describe.md) | Nested describe block should be less than set max value or default value | 🌐 | | |
| [no-alias-methods](docs/rules/no-alias-methods.md) | Disallow alias methods | 🌐 | 🔧 | |
| [no-commented-out-tests](docs/rules/no-commented-out-tests.md) | Disallow commented out tests | ✅ | | |
| [no-conditional-expect](docs/rules/no-conditional-expect.md) | Disallow conditional expects | 🌐 | | |
| [no-conditional-in-test](docs/rules/no-conditional-in-test.md) | Disallow conditional tests | 🌐 | | |
| [no-conditional-tests](docs/rules/no-conditional-tests.md) | Disallow conditional tests | 🌐 | | |
| [no-disabled-tests](docs/rules/no-disabled-tests.md) | Disallow disabled tests | 🌐 | | |
| [no-done-callback](docs/rules/no-done-callback.md) | Disallow using a callback in asynchrounous tests and hooks | 🌐 | | 💡 |
| [no-duplicate-hooks](docs/rules/no-duplicate-hooks.md) | Disallow duplicate hooks and teardown hooks | 🌐 | | |
| [no-focused-tests](docs/rules/no-focused-tests.md) | Disallow focused tests | 🌐 | 🔧 | |
| [no-hooks](docs/rules/no-hooks.md) | Disallow setup and teardown hooks | 🌐 | | |
| [no-identical-title](docs/rules/no-identical-title.md) | Disallow identical titles | ✅ | 🔧 | |
| [no-interpolation-in-snapshots](docs/rules/no-interpolation-in-snapshots.md) | Disallow string interpolation in snapshots | 🌐 | 🔧 | |
| [no-restricted-vi-methods](docs/rules/no-restricted-vi-methods.md) | Disallow specific `vi.` methods | 🌐 | | |
| [no-skipped-tests](docs/rules/no-skipped-tests.md) | Disallow skipped tests | 🌐 | | |
| [prefer-lowercase-title](docs/rules/prefer-lowercase-title.md) | Enforce lowercase titles | 🌐 | 🔧 | |
| [prefer-to-be](docs/rules/prefer-to-be.md) | Suggest using toBe() | ✅ | 🔧 | |

<!-- end auto-generated rules list -->

Expand Down
26 changes: 26 additions & 0 deletions docs/rules/no-interpolation-in-snapshots.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Disallow string interpolation in snapshots (`vitest/no-interpolation-in-snapshots`)

⚠️ This rule _warns_ in the 🌐 `all` config.

🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).

<!-- end auto-generated rule header -->

## Rule Details

This rule aims to prevent the use of string interpolation in snapshots.

### Fail

```ts
expect('foo').toMatchSnapshot(`${bar}`)
expect('foo').toMatchSnapshot(`foo ${bar}`)
```

### Pass

```ts
expect('foo').toMatchSnapshot()
expect('foo').toMatchSnapshot('foo')
expect('foo').toMatchSnapshot(bar)
```
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import noConditionalInTest, { RULE_NAME as noConditionalInTestName } from './rul
import noDisabledTests, { RULE_NAME as noDisabledTestsName } from './rules/no-disabled-tests'
import noDoneCallback, { RULE_NAME as noDoneCallbackName } from './rules/no-done-callback'
import noDuplicateHooks, { RULE_NAME as noDuplicateHooksName } from './rules/no-duplicate-hooks'
import nonInterpolationInSnapShots, { RULE_NAME as noInterpolationInSnapshotsName } from './rules/no-interpolation-in-snapshots'

const createConfig = (rules: Record<string, string>) => ({
plugins: ['vitest'],
Expand Down Expand Up @@ -45,7 +46,8 @@ const allRules = {
[noConditionalInTestName]: 'warn',
[noDisabledTestsName]: 'warn',
[noDoneCallbackName]: 'warn',
[noDuplicateHooksName]: 'warn'
[noDuplicateHooksName]: 'warn',
[noInterpolationInSnapshotsName]: 'warn'
}

const recommended = {
Expand Down Expand Up @@ -76,7 +78,8 @@ export default {
[noConditionalInTestName]: noConditionalInTest,
[noDisabledTestsName]: noDisabledTests,
[noDoneCallbackName]: noDoneCallback,
[noDuplicateHooksName]: noDuplicateHooks
[noDuplicateHooksName]: noDuplicateHooks,
[noInterpolationInSnapshotsName]: nonInterpolationInSnapShots
},
configs: {
all: createConfig(allRules),
Expand Down
78 changes: 78 additions & 0 deletions src/rules/no-interpolation-in-snapshots.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { RuleTester } from '@typescript-eslint/utils/dist/ts-eslint'
import { describe, it } from 'vitest'
import rule, { RULE_NAME } from './no-interpolation-in-snapshots'

describe(RULE_NAME, () => {
const tester = new RuleTester({
parser: require.resolve('@typescript-eslint/parser')
})

it(RULE_NAME, () => {
tester.run(RULE_NAME, rule, {
valid: [
'expect("something").toEqual("else");',
'expect(something).toMatchInlineSnapshot();',
'expect(something).toMatchInlineSnapshot(`No interpolation`);',
'expect(something).toMatchInlineSnapshot({}, `No interpolation`);',
'expect(something);',
'expect(something).not;',
'expect.toHaveAssertions();',
// eslint-disable-next-line no-template-curly-in-string
'myObjectWants.toMatchInlineSnapshot({}, `${interpolated}`);',
// eslint-disable-next-line no-template-curly-in-string
'myObjectWants.toMatchInlineSnapshot({}, `${interpolated1} ${interpolated2}`);',
// eslint-disable-next-line no-template-curly-in-string
'toMatchInlineSnapshot({}, `${interpolated}`);',
// eslint-disable-next-line no-template-curly-in-string
'toMatchInlineSnapshot({}, `${interpolated1} ${interpolated2}`);',
'expect(something).toThrowErrorMatchingInlineSnapshot();',
'expect(something).toThrowErrorMatchingInlineSnapshot(`No interpolation`);'
],
invalid: [
{
// eslint-disable-next-line no-template-curly-in-string
code: 'expect(something).toMatchInlineSnapshot(`${interpolated}`);',
errors: [
{
messageId: 'noInterpolationInSnapshots',
column: 41,
line: 1
}
]
},
{
// eslint-disable-next-line no-template-curly-in-string
code: 'expect(something).not.toMatchInlineSnapshot(`${interpolated}`);',
errors: [
{
messageId: 'noInterpolationInSnapshots',
column: 45,
line: 1
}
]
}, {
// eslint-disable-next-line no-template-curly-in-string
code: 'expect(something).toThrowErrorMatchingInlineSnapshot(`${interpolated}`);',
errors: [
{
endColumn: 71,
column: 54,
messageId: 'noInterpolationInSnapshots'
}
]
},
{
// eslint-disable-next-line no-template-curly-in-string
code: 'expect(something).not.toThrowErrorMatchingInlineSnapshot(`${interpolated}`);',
errors: [
{
endColumn: 75,
column: 58,
messageId: 'noInterpolationInSnapshots'
}
]
}
]
})
})
})
46 changes: 46 additions & 0 deletions src/rules/no-interpolation-in-snapshots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { AST_NODE_TYPES } from '@typescript-eslint/utils'
import { createEslintRule, getAccessorValue } from '../utils'
import { parseVitestFnCall } from '../utils/parseVitestFnCall'

export const RULE_NAME = 'no-interpolation-in-snapshots'
export type MESSAGE_ID = 'noInterpolationInSnapshots'
export type Options = []

export default createEslintRule<Options, MESSAGE_ID>({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Disallow string interpolation in snapshots',
recommended: 'error'
},
fixable: 'code',
schema: [],
messages: {
noInterpolationInSnapshots: 'Do not use string interpolation in snapshots'
}
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
const vitestFnCall = parseVitestFnCall(node, context)

if (vitestFnCall?.type !== 'expect')
return

if (['toMatchInlineSnapshot',
'toThrowErrorMatchingInlineSnapshot'].includes(getAccessorValue(vitestFnCall.matcher))) {
vitestFnCall.args.forEach(argument => {
if (argument.type === AST_NODE_TYPES.TemplateLiteral && argument.expressions.length > 0) {
context.report({
messageId: 'noInterpolationInSnapshots',
node: argument
})
}
})
}
}
}
}
})