Dayem Siddiqui
Dayem Siddiqui

Reputation: 215

Configure ESLint RuleTester to use Typescript Parser

I am trying to write some custom ESLint rules for my typescript based project. In my project I am using eslint/typescript for linting.

I have already written a custom eslint plugin which validates a custom rule. Now I want to write the unit tests for that custom rule. My test file looks like this:

/**
 * @fileoverview This rule verifies that logic can only depend on other logic
 * @author Dayem Siddiqui
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const typescriptParser = require('@typescript-eslint/parser')
var rule = require("../../../lib/rules/logic-dependency"),
  RuleTester = require("eslint").RuleTester;

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
typescriptParser.parseForESLint()
var ruleTester = new RuleTester({ parserOptions: {} });
ruleTester.run("logic-dependency", rule, {
  valid: [
    `class DeleteLogic {

        }
    class CreateLogic {
            constructor(private deleteLogic: DeleteLogic) {}
    }`
  ],

  invalid: [
    {
      code: `class ExternalClient {

            }
            
            class UpdateLogic {
                constructor(private externalClient: ExternalClient) {}
            }`,
      errors: [
        {
          message: "Logic cannot have a dependency on client",
          type: "MethodDefinition"
        }
      ]
    }
  ]
});

Right now my tests a failing because by default eslint only understand plain Javascript code. I understand that I need to somehow configure it to use a custom parser that allows it to understand/parse typescript code. However I am unable to find a good example online on how to do that

Upvotes: 12

Views: 3475

Answers (2)

Sander
Sander

Reputation: 672

The RuleTester constructor takes eslint's parser options that allow for configuring the parser itself. So pass it in like this and Bob's your uncle:

const ruleTester = new RuleTester({
  parser: '@typescript-eslint/parser',
});

typescript-eslint's own rule tests (e.g. this one) use exactly this.

(Was searching for an answer to this question and kept up ending here, so I posted the solution I found here in the hope it'll be useful.)


eslint 6.0+

Incorporating @Sonata's comment:

Eslint 6.0+ requires an absolute path to the parser (see 6.0 migration guide):

const ruleTester = new RuleTester({
  parser: require.resolve('@typescript-eslint/parser'),
});

Upvotes: 13

Thoth
Thoth

Reputation: 2274

Use a package such as the typescript-eslint/parser. I can't provide much more than a link in this case. If you need help using it, let me know.

Upvotes: 0

Related Questions