跳至主要內容

@typescript-eslint/rule-tester

npm: @typescript-eslint/rule-tester v7.13.1

測試 ESLint 規則的實用程式

這是對 ESLint 內建的RuleTester進行的 fork,可提供一些更佳的型別和額外功能來測試 TypeScript 規則。

用法

對於非型別感知規則,您可以按以下方式進行測試

import { RuleTester } from '@typescript-eslint/rule-tester';
import rule from '../src/rules/my-rule.ts';

const ruleTester = new RuleTester();

ruleTester.run('my-rule', rule, {
valid: [
// valid tests can be a raw string,
'const x = 1;',
// or they can be an object
{
code: 'const y = 2;',
options: [{ ruleOption: true }],
},

// you can enable JSX parsing by passing parserOptions.ecmaFeatures.jsx = true
{
code: 'const z = <div />;',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
],
invalid: [
// invalid tests must always be an object
{
code: 'const a = 1;',
// invalid tests must always specify the expected errors
errors: [
{
messageId: 'ruleMessage',
// If applicable - it's recommended that you also assert the data in
// addition to the messageId so that you can ensure the correct message
// is generated
data: {
placeholder1: 'a',
},
},
],
},

// fixers can be tested using the output parameter
{
code: 'const b = 1;',
output: 'const c = 1;',
errors: [
/* ... */
],
},
// passing `output = null` will enforce the code is NOT changed
{
code: 'const c = 1;',
output: null,
errors: [
/* ... */
],
},

// suggestions can be tested via errors
{
code: 'const d = 1;',
output: null,
errors: [
{
messageId: 'suggestionError',
suggestions: [
{
messageId: 'suggestionOne',
output: 'const e = 1;',
},
],
},
],
},
// passing `suggestions = null` will enforce there are NO suggestions
{
code: 'const d = 1;',
output: null,
errors: [
{
messageId: 'noSuggestionError',
suggestions: null,
},
],
},
],
});

感知型別的測試

感知型別的規則可以用幾乎相同的方式進行測試,只不過您需要在磁碟上建立一些檔案。我們在磁碟上要求檔案,這是因為 TypeScript 的一個限制,在於它需要磁碟上的實體檔案來初始化專案。我們建議在附近建立一個包含三個檔案的fixture資料夾

  1. file.ts - 這應為空檔案。
  2. react.tsx - 這應為空檔案。
  3. tsconfig.json - 這是測試應使用的設定擋,例如
    {
    "compilerOptions": {
    "strict": true
    },
    "include": ["file.ts", "react.tsx"]
    }
注意

重要的是,請注意file.tsreact.tsx都必須是空檔!規則測試器會自動使用測試中的字串內容 - 空檔只是用來初始化。

然後,您可以透過提供具備型別感知的功能來測試您的規則

const ruleTester = new RuleTester({
parserOptions: {
tsconfigRootDir: './path/to/your/folder/fixture',
project: './tsconfig.json',
},
});

使用該設定檔,分析器會自動執行具備型別感知的功能,就像從前一樣撰寫測試。

測試依賴限制

有時,您會希望根據多個版本的依賴關係來測試您的規則,以確保向前和向後相容性。在向後相容性測試中,會出現一個複雜情況,即某些測試可能與較舊版本的依賴關係不相容。例如 - 如果您要測試較舊版本的 TypeScript,某些功能可能會導致分析器錯誤!

// `Options` and `RangeOptions` are defined in the 'semver' package.
// We redeclare them here to avoid a peer dependency on that package:
export interface RangeOptions {
includePrerelease?: boolean | undefined;
loose?: boolean | undefined;
}

export interface SemverVersionConstraint {
readonly range: string;
readonly options?: RangeOptions | boolean;
}
export type AtLeastVersionConstraint =
| `${number}.${number}.${number}-${string}`
| `${number}.${number}.${number}`
| `${number}.${number}`
| `${number}`;
export type VersionConstraint =
| AtLeastVersionConstraint
| SemverVersionConstraint;
/**
* Passing a string for the value is shorthand for a '>=' constraint
*/
export type DependencyConstraint = Readonly<Record<string, VersionConstraint>>;

RuleTester 允許您在個別測試或建構函式層級套用依賴限制。

const ruleTester = new RuleTester({
dependencyConstraints: {
// none of the tests will run unless `my-dependency` matches the semver range `>=1.2.3`
'my-dependency': '1.2.3',
// you can also provide granular semver ranges
'my-granular-dep': {
// none of the tests will run unless `my-granular-dep` matches the semver range `~3.2.1`
range: '~3.2.1',
},
},
});

ruleTester.run('my-rule', rule, {
valid: [
{
code: 'const y = 2;',
dependencyConstraints: {
// this test won't run unless BOTH dependencies match the given ranges
first: '1.2.3',
second: '3.2.1',
},
},
],
invalid: [
/* ... */
],
});

dependencyConstraints 物件中所提供的依賴關係必須與指定的範圍相符,才能不略過測試。

使用特定框架

ESLint 的RuleTester依賴一些全域測試掛勾。如果它們在全域中不可用,您的測試會傳回錯誤,例如

Error: Missing definition for `afterAll` - you must set one using `RuleTester.afterAll` or there must be one defined globally as `afterAll`.
提示

請務必第一次呼叫new RuleTester(...)之前設定RuleTester的靜態屬性。

Mocha

請考慮在mochaGlobalSetup歷程中設定RuleTester的靜態屬性

import * as mocha from 'mocha';
import { RuleTester } from '@typescript-eslint/rule-tester';

RuleTester.afterAll = mocha.after;

Vitest

請考慮在setupFiles指令碼中設定RuleTester的靜態屬性

import * as vitest from 'vitest';
import { RuleTester } from '@typescript-eslint/rule-tester';

RuleTester.afterAll = vitest.afterAll;

// If you are not using vitest with globals: true (https://vitest.dev.org.tw/config/#globals):
RuleTester.it = vitest.it;
RuleTester.itOnly = vitest.it.only;
RuleTester.describe = vitest.describe;

節點內建測試執行程序

請考慮使用 --import--require 旗標,於預先載入的模組中設定 RuleTester 的靜態屬性

// setup.js
import * as test from 'node:test';
import { RuleTester } from '@typescript-eslint/rule-tester';

RuleTester.afterAll = test.afterAll;
RuleTester.describe = test.describe;
RuleTester.it = test.it;
RuleTester.itOnly = test.it.only;

如此一來,就能透過下列方式從命令列執行測試

node --import setup.js --test

選項

RuleTester 建構函式選項

import type {
ClassicConfig,
ParserOptions,
} from '@typescript-eslint/utils/ts-eslint';

import type { DependencyConstraint } from './DependencyConstraint';

export interface RuleTesterConfig extends ClassicConfig.Config {
/**
* The default parser to use for tests.
* @default '@typescript-eslint/parser'
*/
readonly parser: string;
/**
* The default parser options to use for tests.
*/
readonly parserOptions?: Readonly<ParserOptions>;
/**
* Constraints that must pass in the current environment for any tests to run.
*/
readonly dependencyConstraints?: DependencyConstraint;
/**
* The default filenames to use for type-aware tests.
* @default { ts: 'file.ts', tsx: 'react.tsx' }
*/
readonly defaultFilenames?: Readonly<{
ts: string;
tsx: string;
}>;
}

有效的測試案例選項

import type {
Linter,
ParserOptions,
SharedConfigurationSettings,
} from '@typescript-eslint/utils/ts-eslint';

import type { DependencyConstraint } from './DependencyConstraint';

export interface ValidTestCase<Options extends Readonly<unknown[]>> {
/**
* Name for the test case.
*/
readonly name?: string;
/**
* Code for the test case.
*/
readonly code: string;
/**
* Environments for the test case.
*/
readonly env?: Readonly<Linter.EnvironmentConfig>;
/**
* The fake filename for the test case. Useful for rules that make assertion about filenames.
*/
readonly filename?: string;
/**
* The additional global variables.
*/
readonly globals?: Readonly<Linter.GlobalsConfig>;
/**
* Options for the test case.
*/
readonly options?: Readonly<Options>;
/**
* The absolute path for the parser.
*/
readonly parser?: string;
/**
* Options for the parser.
*/
readonly parserOptions?: Readonly<ParserOptions>;
/**
* Settings for the test case.
*/
readonly settings?: Readonly<SharedConfigurationSettings>;
/**
* Run this case exclusively for debugging in supported test frameworks.
*/
readonly only?: boolean;
/**
* Skip this case in supported test frameworks.
*/
readonly skip?: boolean;
/**
* Constraints that must pass in the current environment for the test to run
*/
readonly dependencyConstraints?: DependencyConstraint;
}

無效的測試案例選項

import type { AST_NODE_TYPES, AST_TOKEN_TYPES } from '@typescript-eslint/utils';
import type { ReportDescriptorMessageData } from '@typescript-eslint/utils/ts-eslint';

import type { DependencyConstraint } from './DependencyConstraint';
import type { ValidTestCase } from './ValidTestCase';

export interface SuggestionOutput<MessageIds extends string> {
/**
* Reported message ID.
*/
readonly messageId: MessageIds;
/**
* The data used to fill the message template.
*/
readonly data?: ReportDescriptorMessageData;
/**
* NOTE: Suggestions will be applied as a stand-alone change, without triggering multi-pass fixes.
* Each individual error has its own suggestion, so you have to show the correct, _isolated_ output for each suggestion.
*/
readonly output: string;

// we disallow this because it's much better to use messageIds for reusable errors that are easily testable
// readonly desc?: string;
}

export interface TestCaseError<MessageIds extends string> {
/**
* The 1-based column number of the reported start location.
*/
readonly column?: number;
/**
* The data used to fill the message template.
*/
readonly data?: ReportDescriptorMessageData;
/**
* The 1-based column number of the reported end location.
*/
readonly endColumn?: number;
/**
* The 1-based line number of the reported end location.
*/
readonly endLine?: number;
/**
* The 1-based line number of the reported start location.
*/
readonly line?: number;
/**
* Reported message ID.
*/
readonly messageId: MessageIds;
/**
* Reported suggestions.
*/
readonly suggestions?: readonly SuggestionOutput<MessageIds>[] | null;
/**
* The type of the reported AST node.
*/
readonly type?: AST_NODE_TYPES | AST_TOKEN_TYPES;

// we disallow this because it's much better to use messageIds for reusable errors that are easily testable
// readonly message?: string | RegExp;
}

export interface InvalidTestCase<
MessageIds extends string,
Options extends Readonly<unknown[]>,
> extends ValidTestCase<Options> {
/**
* Expected errors.
*/
readonly errors: readonly TestCaseError<MessageIds>[];
/**
* The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
*/
readonly output?: string | null;
/**
* Constraints that must pass in the current environment for the test to run
*/
readonly dependencyConstraints?: DependencyConstraint;
}