AssertionError 'import' is reserved when writing tests for custom eslint rule - eslint

The custom eslint rule runs ok in our project, but I cannot figure out how to run tests for it. My guess is that I am running wrong version of ecmascript and I need to use babel or adjust something in eslintrc.json to make this work with the mocha scripts.
Getting error message:
AssertionError [ERR_ASSERTION]: A fatal parsing error occurred: Parsing error: The keyword 'import' is reserved
The test:
/**
* #fileoverview Prohibit import underscore to help tree
* #author Jason Hocker
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/no-full-lodash-import"),
RuleTester = require("eslint").RuleTester;
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester();
ruleTester.run("no-full-lodash-import", rule, {
valid: [
{code: "import os from \"os\";\nimport fs from \"fs\";" },
{code: "import { merge } from \"lodash-es\";"}
],
invalid: [
{
code: "import _ from 'lodash';",
errors: [{
message: "Fill me in.",
type: "Me too"
}]
}
]
});
One of the .jslintrc.json files I tried:
{
"env": {
"browser": true,
"es6": true,
"mocha": true // add mocha as true to your ".eslintrc. *" file
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error"
}
}

ESLint docs suggest that you can pass a configuration object to the RuleTester constructor.
In your case it should probably look like this:
var config = {
env: {
browser: true,
es6: true,
mocha: true, // add mocha as true to your ".eslintrc. *" file
},
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
}
var ruleTester = new RuleTester()

Related

Display prettier linting errors in vite hmr overlay with svelte

I have a Svelte app with Vite bundler. My linter is Eslint with Prettier and vite-plugin-svelte plugins. Linting works well, but I want to make the app show all the linting errors inside Vite hmr overlay, same way it works with syntax errors as in this picture
My question is: Is it even possible to make something like that with Vite? I found nothing helpful about Vite's hmr overlay in the documentation, or maybe I just missing something in Eslint/Prettier config?
Here is config files:
.eslintrc :
{
"extends": ["eslint:recommended", "airbnb-base", "prettier"],
"plugins": ["svelte3", "prettier"],
"env": {
"es6": true,
"browser": true,
"node": true
},
"overrides": [
{
"files": ["*.svelte"],
"processor": "svelte3/svelte3"
}
],
"parserOptions": {
"project": "./jsconfig.json"
},
"rules": {
"prefer-arrow-callback": "off",
"arrow-body-style": "off",
"import/prefer-default-export": "off",
"import/no-anonymous-default-export": [
"error",
{
"allowArray": true,
"allowArrowFunction": false,
"allowAnonymousClass": false,
"allowAnonymousFunction": false,
"allowCallExpression": true,
"allowLiteral": false,
"allowObject": true
}
],
"dot-notation": "off"
}
}
.prettierrc.js
module.exports = {
arrowParens: 'always',
bracketSpacing: true,
endOfLine: 'lf',
printWidth: 80,
singleQuote: true,
tabWidth: 2,
trailingComma: 'all',
overrides: [
{
files: 'package*.json',
options: {
printWidth: 1000,
},
},
],
};
vite.config.js
export default defineConfig({
plugins: [
svelte({
preprocess: preprocess(),
}),
],
});
If it's possible to write your own vite plugin or modify the one in question, adding throw new Error(YOUR_ERROR) in the right plugin hook will trigger the overlay. e.g: modifying this example
https://vitejs.dev/guide/api-plugin.html#transformindexhtml
const htmlPlugin = () => {
return {
name: 'html-transform',
transformIndexHtml(html) {
// ADD THROW LINE
throw new Error("this will showup in an overlay")
}
}
}
Will lead to...

ESLint with Mocha

I am trying to use ESLint for mocha, but for some reason the rules don'y apply and the linting passes.
My config file:
module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true,
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
"expect": "true"
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
overrides: [
{
files: [
"**/*.test.js"
],
env: {
mocha: true
},
plugins: ["mocha"],
rules: {
"mocha/no-exclusive-tests": "error",
"mocha/no-pending-tests": "error"
}
}
]
};
My test file only includes one line:
it('should throw a lint error')
The linter should find an error because of the 'no pending tests' rule, yet when I run the test file with eslint the linting passes as a success.
I have no idea why. I looked it up online and it seems like my configuration file is good as it is.
your solution is the same as this post answer.
However, the one that suits you better is the one you only edit the .eslintrc file as shown in eslint-configuration-doc, which would go like this:
module.exports = {
env: {
browser: false,
es6: true,
node: true,
mocha: true
}
// More code to go on that is not relative to your question ...
}
The line you are aiming is the one with
mocha: true
This solution worked for me.
{
"env": {
"browser": true,
"es6": true,
"mocha": true // add mocha as true to your ".eslintrc. *" file
}
}

Nuxt.js: importing `vuex` emits eslint(import/no-extraneous-dependencies) error

Nuxt.js is shipped with vuex as dependency so importing it doesn't require me to specify it in package.json.
But as vuex is not in package.json, whenever I try to import vuex, eslint emits import/no-extraneous-dependencies error.
In this case, how can I tell eslint to vuex is already included in nuxt module? Or is there any workaround to ignore some modules, ie. vuex, vue...
Below is my current eslint rules.
// .eslintrc.js
const path = require('path')
module.exports = {
env: {
browser: true,
es6: true,
jest: true
},
extends: [
'airbnb-base',
'plugin:vue/recommended',
'plugin:vue-types/strongly-recommended',
'plugin:prettier/recommended',
'#vue/prettier'
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly'
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
plugins: ['prettier', 'vue'],
rules: {
'prettier/prettier': 'error',
'no-console': 0,
'import/prefer-default-export': 0,
'import/no-unresolved': 0,
'vue/max-attributes-per-line': 0
}
}
You can specify vuex as core-modules.
reference
// .eslintrc.js
settings: {
'import/core-modules': ['vue', 'vuex'] // these modules are included in nuxt.js
}
You can ignore these modules as following:
'node/no-extraneous-import': [
'error',
{
allowModules: ['vue', 'vuex']
}
]

eslint parsing error: Parsing error: Unexpected token =>

I'm using node v7.10.0 that supports ES6 and because of that I don't transpile my code.
ESLint v3.19.0 gives a error Parsing error: Unexpected token => at the following code.
Give errors:
module.exports = {
index: async (req, res) => {
await functionThatReturnsSomePromise();
}
}
Also when I just use function it fails with the error Parsing error: Unexpected token function
Give errors:
module.exports = {
index: async function(req, res) {
await functionThatReturnsSomePromise();
}
}
When I define a class like this the linter doesn't complain about it:
No errors:
class test {
testing() {
async () => {
console.log('test');
}
}
}
.eslintrc
{
"extends": "eslint:recommended",
"ecmaFeatures": {
"binaryLiterals": true, // enable binary literals
"blockBindings": true, // enable let and const (aka block bindings)
"defaultParams": true, // enable default function parameters
"forOf": true, // enable for-of loops
"generators": true, // enable generators
"objectLiteralComputedProperties": true, // enable computed object literal property names
"objectLiteralDuplicateProperties": true, // enable duplicate object literal properties in strict mode
"objectLiteralShorthandMethods": true, // enable object literal shorthand methods
"objectLiteralShorthandProperties": true, // enable object literal shorthand properties
"octalLiterals": true, // enable octal literals
"regexUFlag": true, // enable the regular expression u flag
"regexYFlag": true, // enable the regular expression y flag
"templateStrings": true, // enable template strings
"unicodeCodePointEscapes": true, // enable code point escapes
"jsx": true // enable JSX
},
"env": {
"browser": false, // browser global variables.
"node": true, // Node.js global variables and Node.js-specific rules.
"es6": true, // for ES6
"amd": false, // defines require() and define() as global variables as per the amd spec.
"mocha": true, // adds all of the Mocha testing global variables.
"jasmine": false, // adds all of the Jasmine testing global variables for version 1.3 and 2.0.
"phantomjs": false, // phantomjs global variables.
"jquery": false, // jquery global variables.
"prototypejs": false, // prototypejs global variables.
"shelljs": false // shelljs global variables.
},
"globals": {
// e.g. "angular": true
},
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module",
"ecmaFeatures": {
arrowFunctions: true,
defaultParams: true
}
},
"rules": {
////////// Stylistic Issues //////////
"no-underscore-dangle": 0, // disallow dangling underscores in identifiers
////////// ECMAScript 6 //////////
"no-var": 2 // require let or const instead of var (off by default)
}
}
How can I fix this?
I solved this problem by editing:
parserOptions.ecmaVersion = 8
async/await is in ES8 (aka ES2017) which I considered is in ES7 😉
Since your code needs to be transpiled, have you tried to use the babel-eslint parser?
To do so, install the babel-eslint package and include in your .eslintrc.json (or js equivalent):
{
(...)
"parser": "babel-eslint",
(...)
}
At the end I use a different linter that works fine.
I'm now using eslint 3.10.1

How do I use Node Typescript types with Karma-Webpack

I have Webpack configured for transpiling my TS files in Karma. I have also included Node and CoreJS types. However, when I try to run my tests I get...
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
I tried adding webpack-env using npm install --save-dev #types/webpack-env, but that gives me even more errors.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(183,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'RequireFunction'.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(232,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type 'NodeModule', but here has type 'Module'.
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
My Karma config looks like this...
var webpack = require("webpack");
module.exports = function(config) {
var webpackConfig = require("../../webpack.config");
// TODO: Can we get rid on this?
// We need to remove entry points and plugins
webpackConfig.plugins = [
// IMPORTANT!!!! Without this source maps fail to show up.
new webpack.SourceMapDevToolPlugin({
filename: null, // if no value is provided the sourcemap is inlined
test: /\.(ts|js)($|\?)/i // process .js and .ts files only
})
];
//This is used to remap can access (Based on https://github.com/sshev/karma-remap-coverage)
webpackConfig.ts = {
compilerOptions: {
inlineSourceMap: true,
sourceMap: false
}
};
webpackConfig.module.postLoaders = [
{
test: /^((?!\.spec\.ts).)*.ts$/,
exclude: /(node_modules|bower_components)/,
loader: 'istanbul-instrumenter'
}
];
webpackConfig.entry = {};
var configuration = {
autoWatch: true,
basePath: "",
browsers: ["Chrome"],
colors: true,
concurrency: Infinity,
coverageReporter: {
type: 'in-memory'
},
exclude: [
"node_modules"
],
files: [
{ pattern: "./test.bundle.ts", watched: true },
],
frameworks: ["jasmine"],
htmlReporter: {
outputFile: "../../reports/units.html"
},
logLevel: config.LOG_INFO,
port: 9876,
preprocessors: {
"./test.bundle.ts": ["webpack", "sourcemap" ],
},
remapCoverageReporter: {
"text-summary": null,
html: "./reports/coverage/html"
},
reporters: ["progress", "coverage", "remap-coverage", "html"],
singleRun: false,
webpack: webpackConfig,
webpackMiddleware: { stats: "errors-only"}
};
config.set(configuration);
};
Versions
webpack 1.14.0, node v6.9.2, Typescript 2.1.4

Resources