A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://typescript-eslint.io/packages/rule-tester below:

@typescript-eslint/rule-tester | typescript-eslint

@typescript-eslint/rule-tester

A utility for testing ESLint rules

This is a fork of ESLint's built-in RuleTester to provide some better types and additional features for testing TypeScript rules.

Usage

For non-type-aware rules you can test them as follows:

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: [

'const x = 1;',

{
code: 'const y = 2;',
options: [{ ruleOption: true }],
},


{
code: 'const z = <div />;',
languageOptions: {
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
},
],
invalid: [

{
code: 'const a = 1;',

errors: [
{
messageId: 'ruleMessage',



data: {
placeholder1: 'a',
},
},
],
},


{
code: 'const b = 1;',
output: 'const c = 1;',
errors: [

],
},

{
code: 'const c = 1;',
output: null,
errors: [

],
},


{
code: 'const d = 1;',
output: ['const e = 1;', 'const f = 1;'],
errors: [

],
},


{
code: 'const d = 1;',
output: null,
errors: [
{
messageId: 'suggestionError',
suggestions: [
{
messageId: 'suggestionOne',
output: 'const e = 1;',
},
],
},
],
},

{
code: 'const d = 1;',
output: null,
errors: [
{
messageId: 'noSuggestionError',
suggestions: null,
},
],
},
],
});
Type-Aware Testing

Type-aware rules can be tested in almost exactly the same way as regular code, using parserOptions.projectService. Most rule tests specify parserOptions.allowDefaultProject: ["*.ts*"] to enable type checking on all test files.

You can then test your rule by providing the type-aware config:

const ruleTester = new RuleTester({
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['*.ts*'],
},
tsconfigRootDir: './path/to/your/folder/fixture',
},
},
});

With that config the parser will automatically run in type-aware mode and you can write tests just like before.

When not specified with a filename option, RuleTester uses the following test file names:

Test Dependency Constraints

Sometimes it's desirable to test your rule against multiple versions of a dependency to ensure backwards and forwards compatibility. With backwards-compatibility testing there comes a complication in that some tests may not be compatible with an older version of a dependency. For example - if you're testing against an older version of TypeScript, certain features might cause a parser error!



export interface RangeOptions {
includePrerelease?: boolean | undefined;
loose?: boolean | undefined;
}

export interface SemverVersionConstraint {
readonly options?: boolean | RangeOptions;
readonly range: string;
}
export type AtLeastVersionConstraint =
| `${number}.${number}.${number}-${string}`
| `${number}.${number}.${number}`
| `${number}.${number}`
| `${number}`;
export type VersionConstraint =
| AtLeastVersionConstraint
| SemverVersionConstraint;



export type DependencyConstraint = Readonly<Record<string, VersionConstraint>>;

The RuleTester allows you to apply dependency constraints at either an individual test or constructor level.

const ruleTester = new RuleTester({
dependencyConstraints: {

'my-dependency': '1.2.3',

'my-granular-dep': {

range: '~3.2.1',
},
},
});

ruleTester.run('my-rule', rule, {
valid: [
{
code: 'const y = 2;',
dependencyConstraints: {

first: '1.2.3',
second: '3.2.1',
},
},
],
invalid: [

],
});

All dependencies provided in the dependencyConstraints object must match their given ranges in order for a test to not be skipped.

With Specific Frameworks

ESLint's RuleTester relies on some global hooks for tests. If they aren't available globally, your tests will fail with an error like:

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

tip

Be sure to set RuleTester's static properties before calling new RuleTester(...) for the first time.

Mocha

Consider setting up RuleTester's static properties in a mochaGlobalSetup fixture:

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

RuleTester.afterAll = mocha.after;
Node.js (node:test)

Consider setting up RuleTester's static properties in a preloaded module using the --import or --require flag:


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

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

Tests can then be run from the command line like so:

node --import setup.js --test
Vitest

Consider setting up RuleTester's static properties in a setupFiles script:

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

RuleTester.afterAll = vitest.afterAll;


RuleTester.it = vitest.it;
RuleTester.itOnly = vitest.it.only;
RuleTester.describe = vitest.describe;
Other Frameworks

In general, RuleTester can support any test framework that exposes hooks for running code before or after rules. From RuleTester's Static Properties, assign any of the following that the running test framework supports.

I.e.:

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

RuleTester.afterAll = test.after;
RuleTester.describe = test.describe;
RuleTester.it = test.it;
RuleTester.itOnly = test.it.only;
Options RuleTester constructor options
import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint';

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




export interface RuleTesterConfig extends FlatConfig.Config {




readonly defaultFilenames?: Readonly<{
ts: string;
tsx: string;
}>;



readonly dependencyConstraints?: DependencyConstraint;
}
Valid test case options
import type {
Linter,
Parser,
ParserOptions,
SharedConfigurationSettings,
} from '@typescript-eslint/utils/ts-eslint';

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

export interface TestLanguageOptions {



readonly env?: Readonly<Linter.EnvironmentConfig>;



readonly globals?: Readonly<Linter.GlobalsConfig>;



readonly parser?: Readonly<Parser.LooseParserModule>;



readonly parserOptions?: Readonly<ParserOptions>;
}

export interface ValidTestCase<Options extends readonly unknown[]> {



readonly after?: () => void;



readonly before?: () => void;



readonly code: string;



readonly dependencyConstraints?: DependencyConstraint;



readonly filename?: string;



readonly languageOptions?: TestLanguageOptions;



readonly name?: string;



readonly only?: boolean;



readonly options?: Readonly<Options>;



readonly settings?: Readonly<SharedConfigurationSettings>;



readonly skip?: boolean;
}
Invalid test case options
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> {



readonly data?: ReportDescriptorMessageData;



readonly messageId: MessageIds;




readonly output: string;



}

export interface TestCaseError<MessageIds extends string> {



readonly column?: number;



readonly data?: ReportDescriptorMessageData;



readonly endColumn?: number;



readonly endLine?: number;



readonly line?: number;



readonly messageId: MessageIds;



readonly suggestions?: readonly SuggestionOutput<MessageIds>[] | null;



readonly type?: AST_NODE_TYPES | AST_TOKEN_TYPES;



}

export interface InvalidTestCase<
MessageIds extends string,
Options extends readonly unknown[],
> extends ValidTestCase<Options> {



readonly dependencyConstraints?: DependencyConstraint;



readonly errors: readonly TestCaseError<MessageIds>[];



readonly output?: string | string[] | null;
}
Static Properties

Each of the following properties may be assigned to as static members of the RuleTester class.

For example, to assign afterAll:

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

RuleTester.afterAll = () => {

};
afterAll

Runs after all the tests in this file have completed.

describe

Creates a test grouping.

describeSkip

Skips running the tests inside this describe.

it

Creates a test closure.

itOnly

Skips all other tests in the current file.

itSkip

Skips running this test.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4