Search code examples
typescriptjestjsejstypescript-eslint

How can I validate an ejs template of a typescript file with typescript-eslint


I have an ejs template for a typescript file, I need to write a Unit Test with #jest to validate the rendered typescript output of my template using #typescript-eslint (not tslint because it will be deprecated soon: https://medium.com/palantir/tslint-in-2019-1a144c2317a9)

So, I need to require the typescript-eslint module in my spec file and run the validation of my rendered ejs by code like:

it('should be valid typescript file', () => {
        return ejs.renderFile('my-ejs-template.ts.ejs', {}).then(async (view) => {
            const eslint = require('@typescript-eslint/eslint-plugin');
            // what is next ???
        });
    });

Any help will be very appreciated


Solution

  • First install the following modules in devDependencies:

    • @typescript-eslint/eslint-plugin
    • @typescript-eslint/parser

    Second, import the module eslint in your spec file as follows:

    const eslint = require('eslint');
    

    Third, create an .eslintrc.js configuration file to parse typescript files, like:

    module.exports = {
      env: {
        node: true,
        es6: true,
      },
      extends: ['plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      parserOptions: {
        sourceType: 'module',
        typescript: true,
        modules: true,
        ecmaVersion: 6,
        ecmaFeatures: {
          experimentalObjectRestSpread: true,
        },
      },
      plugins: ['@typescript-eslint'],
      rules: {
        indent: ['error', 4],
        'linebreak-style': ['error', 'unix'],
        quotes: ['error', 'single'],
        semi: ['error', 'always'],
      },
    };
    

    Then, import the above config file in your spec file and create a function to get the linter:

    const configTsEslint = require('.eslintrc-typescript');
    const tsLinter = () => {
        const Linter = eslint.Linter;
        return new Linter();
    };
    

    Finally, validate your typescript file as follows:

    it('should be valid typescript file', () => {
            return ejs.renderFile('my-ejs-template.ts.ejs', {}).then(async (view) => {
                const result = tsLinter().verifyAndFix(view);
                expect(result.messages).toStrictEqual([]);
                expect(result.fixed).toBe(true);
            });
        });
    

    You can add rules that are supported by [typescript-eslint][1]