False positives for `no-unused-vars` - eslint

I'm getting a lot of incorrect ESLint/TS warnings saying enum cases are "Assigned a value but never used" or that imports are "defined but never used". Here's some code.
All the imports are saying they're defined but never used (though you can see they are in the types at the bottom).
All the enum cases are saying they're "Assigned a value but never used", and you can see that they are indeed used in all the action types.
I will note, though, that PARAMETER_CHANGE_FAILED also says "Unused readonly field PARAMETER_CHANGE_FAILED" which is actually true, that case is never actually used in my project.
import {ThunkAction, ThunkDispatch} from "redux-thunk";
import {AppState} from "../reducers/index.reducer";
export type ChangeParameterAction = {
type: MyActionType.PARAMETER_CHANGED,
parameter: ParameterName,
value: any
}
export type SetParametersAction = {
type: MyActionType.PARAMETERS_SET,
settings: { [name: string]: any }
}
export type ActiveTabAction = {
type: MyActionType.TAB_CHANGED,
tab: Tab
}
export type ErrorAction = {
type: MyErrorType,
error: Error
}
export enum MyErrorType{
ERROR = 'ERROR',
PARAMETER_CHANGE_FAILED = 'PARAMETER_CHANGE_FAILED',
}
export enum MyActionType{
TAB_CHANGED = 'TAB_CHANGED',
PARAMETER_CHANGED = 'PARAMETER_CHANGED',
PARAMETERS_SET = 'PARAMETERS_SET',
}
export type SettingsAction = ChangeParameterAction | SetParametersAction;
export type FirmmAction =
| ActiveTabAction
| UpdateActiveSeriesAction
| UpdateStudyAction
| UpdateDataAction
| SettingsAction
| ErrorAction
export type MyThunkAction = ThunkAction<void, AppState, {}, MyAction>
export type MyThunkDispatch = ThunkDispatch<{}, {}, MyAction>
In another file, I import pretty much everything from the file above, and use them all (Webstorm's 'Optimize Imports' has been run) but all the types are showing as never used. Interestingly, two of the imported enums aren't giving this false positive error, although one of them is.
I can set no-unused-vars to off in my eslint config, but I'd rather have it actually work properly.
Here's some config info:
// eslintrc
module.exports = {
env: {
browser: true,
es6: true,
},
extends: [
'react-app',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: [
'react',
'#typescript-eslint',
],
rules: {
// TODO: Adding this rule
// "no-unused-vars": "off"
},
};
// package.json dependencies
...
"eslint-config-react-app": "^3.0.5",
"eslint-loader": "2.1.1",
"eslint-plugin-flowtype": "2.50.1",
"eslint-plugin-typescript": "^1.0.0-rc.3",
...
// package.json devDependencies
...
"#typescript-eslint/eslint-plugin": "^2.7.0",
"#typescript-eslint/parser": "^2.7.0",
"eslint": "^6.6.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.16.0",
"eslint-plugin-react-hooks": "^1.7.0",
...

In my case, it helped to use #vue/eslint-config-typescript/recommended configuration.
I also had to install:
eslint-config-typescript (v5, previously I had v4)
#typescript-eslint/eslint-plugin
#typescript-eslint/parser
As suggested here: eslint-config-typescript, I used the following config:
extends: [
'plugin:vue/essential',
'#vue/typescript/recommended', // corrects the 'no-unused-vars'
'#vue/prettier',
'#vue/prettier/#typescript-eslint', // for prettier to work
],

Related

Mongoose is causing 100+ type errors that break the build?

I am trying to get a server build running for a small API. However, I've been hitting a painful problem. Mongoose fails to compile under TypeScript, due to it's internal build of MongoDB. This problem is similar but not an exact repeat of others - I've found a few of them, but their solutions have not worked.
This is the kind of output I've gotten, error wise:
> servapi#1.0.0 clean
> node node_modules/rimraf/bin lib
node_modules/mongodb/mongodb.d.ts:3571:117 - error TS1005: '?' expected.
3571 export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
node_modules/mongodb/mongodb.d.ts:3571:127 - error TS1005: ';' expected.
3571 export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
node_modules/mongodb/mongodb.d.ts:3571:131 - error TS1005: ';' expected.
3571 export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
node_modules/mongodb/mongodb.d.ts:3571:166 - error TS1005: ',' expected.
3571 export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
node_modules/mongodb/mongodb.d.ts:3571:195 - error TS1005: '(' expected.
3571 export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
node_modules/mongodb/mongodb.d.ts:4021:7 - error TS1005: ',' expected.
4021 *
~~~~~~~~~~~
Found 114 errors.
Basically..everything in mongodb fails. I get multiple such type errors. External types are no longer maintained, so those cannot be installed to help.
Updating Mongoose and MongoDB to the latest version at least reduced the errors from 200+.
This is my current tsconfig and package.json:
tsconfig:
{
"compilerOptions": {
"outDir": "lib",
"target": "es6",
"module": "commonjs",
"strict": false,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"strictNullChecks": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": [
"src",
"src/data"
],
"exclude": [
"node_modules"
]
}
package.json:
{
"private": true,
"name": "servapi",
"version": "1.0.0",
"description": "API Server",
"main": "lib/index.js",
"directories": {
"data": "src/data"
},
"scripts": {
"start": "ts-node-dev --respawn --transpile-only src/index.ts",
"build": "npm run clean && tsc && node node_modules/copyfiles/copyfiles package.json ./lib && node node_modules/copyfiles/copyfiles ./lib",
"clean": "node node_modules/rimraf/bin lib"
},
"author": "",
"license": "UNLICENSED",
"devDependencies": {
"#types/cors": "^2.8.6",
"#types/express": "^4.17.1",
"#types/mocha": "^8.2.3",
"copyfiles": "^2.4.1",
"mocha": "^9.0.2",
"rimraf": "^2.7.1",
"ts-node": "^8.1.0",
"ts-node-dev": "^1.0.0-pre.63",
"typescript": "^3.7.0"
},
"dependencies": {
"#types/multer": "^1.4.7",
"axios": "^0.22.0",
"cors": "^2.8.5",
"escape-goat": "^4.0.0",
"express": "^4.16.4",
"mongoose": "^6.3.8",
"multer": "^1.4.5-lts.1"
}
}
It does appear to at least partially build, but halts when it hits the index.js. Adding "skipLibCheck" doesn't seem to work - my guess would be because MongoDB is being called by Mongoose. How can I fix these type errors?
The answer actually turned out to be a TypeScript problem.
For whatever reason, earlier versions don't like the current typing in Mongo/ose, etc. If you come across this problem - upgrade to the latest TypeScript version if you can do so.
For me, that was by forcing TS to the latest version (mine was around 4.7.2) - Remove the ~ in your package.json, change the TypeScript version manually and do an NPM Update.

Jest and Babel transpilation - SyntaxError: Cannot use import statement outside a module

I struggle to use JEST for some cases where running the tests I get
Test suite failed to run
...node_modules\p-retry\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import retry from 'retry';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import pRetry from 'p-retry';
| ^
2 |
3 | export function Retry(tries: number) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/common/Retry.ts:1:1)
Meanwhile my webpack build works nice with typescript and babel. I tried a lot of stuff (see below to get it working but no success so far - and haven't really been able to understand whats going on. From my pov - though the transpilation stuff is kind of a black area so far for me I tried to enable Jest to use ESModules andprovide code as such as well as tried providing commonJS module code.
So I am looking for alternative options and ways to investigate further. Particularly one thing strikes me as strange:
the Retry.ts file from the error is one of my files which imports the pRetry (a node_module written in ESModule style) which in its code does the import retry from 'retry' (another node-module written in commonJS style)from the very first line of the error.
So what seems to happen to me is that the pRetry is not transformed from it's ESModule Code (the source of pRetry starts with import retry from 'retry';) and just wrapped in some commonJS code instead if I interpret the syntax correctly.
So my next steps would likely be investigate what babel-jest really generates and check what's up there and try to deduct furhter. Does anybody know how to achieve this (especially understand what babel-jest generates) or has another idea?
Things I tried - all failed (sometimes slightly different errors)
using plugins: ["#babel/plugin-transform-runtime"] in babel.config.js
changing target and module in tsconfig.json to es5
introducing below in jest.config.ts transformIgnorePatterns: ["node_modules/?!(p-retry)"]
using the following in jest.config.ts
preset: "ts-jest",
transform: {
'^.+\.(ts|tsx)?$': 'ts-jest',
"^.+\.(js|jsx)$": "babel-jest"}
or alternatively with ts-jest for both or babel-jest for both
migrating from .babelrc file to babel.config.js as suggested by one post
AllowJS : true in tscfonfig.json and transformIgnorePatterns in jest in combination
adding ["#babel/plugin-transform-runtime",{"regenerator": true}] to babel.config
Using
preset: "ts-jest",
testEnvironment: "node",
transform: {"node_modules/p-retry/.+\.(j|t)sx?$": "ts-jest"},
transformIgnorePatterns: ["node_modules/(?!p-retry/.*)"]
in jest.config
using "transform-es2015-modules-commonjs" in babel.config
using #babel/plugin-transform-modules-commonjs in babel.config
Applying the following steps as suggest by https://stackoverflow.com/questions/35756479/does-jest-support-es6-import-export#:~:text=Jest%20will%20enable%20compilation%20from,json%20.&text=If%20you%20don't%20want%20to%20pollute%20your%20project%20with%20
Make sure you don't transform away import statements by setting
transform: {} in config file
Run node#^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
Run your test with jest-environment-node or jest-environment-jsdom-sixteen.
playing with testenvironment like jest-environment-node, node or jsdom in jest.config.ts
jest-config.ts:
const tsconfig = require("./tsconfig.json");
const moduleNameMapper = require("tsconfig-paths-jest")(tsconfig)
export default {
collectCoverage: true,
coverageDirectory: "analysis/coverage",
coveragePathIgnorePatterns: ["/node_modules/"],
collectCoverageFrom: ["src/**/*.{js,jsx,ts}"],
coverageReporters: ["json", "lcov", "text", "clover"],
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
statements: 0
},
},
clearMocks: true,
coverageProvider: "babel",
moduleNameMapper,
roots: ["<rootDir>/src/", "<rootDir>/test/"],
testEnvironment: 'jest-environment-node',
testPathIgnorePatterns: [
"\\\\node_modules\\\\"
],
"transform": {
"^.+\\.(js|ts|jsx)$": "babel-jest"
}
};
babel.config.js:
module.exports = {
presets: ['#babel/preset-typescript',
['#babel/preset-env', {
targets: { node: "current" }
}],
'#babel/preset-flow',
],
plugins: [["#babel/plugin-transform-modules-commonjs"], ["#babel/plugin-proposal-decorators", { "legacy": true }], ["#babel/plugin-proposal-class-properties"]]
}
Extract from package.json
"#babel/core": "^7.16.12",
"#babel/plugin-proposal-decorators": "^7.16.5",
"#babel/plugin-transform-modules-commonjs": "^7.16.8",
"#babel/plugin-transform-runtime": "^7.16.10",
"#babel/preset-env": "^7.14.4",
"#babel/preset-flow": "^7.16.7",
"#babel/preset-typescript": "^7.13.0",
"#babel/runtime": "^7.16.7",
"babel-jest": "^27.4.6",
"babel-plugin-transform-regenerator": "^6.26.0",
"jest": "^27.0.4",
"jest-config": "^27.4.5",
"jest-esm-transformer": "^1.0.0",
"ts-jest": "^27.1.3",
"tsconfig-paths-jest": "^0.0.1",
"core-js": "^3.20.0",
Turns out I was close.
With a change of babel.config.ts by adding esmodules: false it is done :-)
module.exports = {
presets: ['#babel/preset-typescript',
['#babel/preset-env', {
targets: { esmodules: false, node: "current" }
}],
'#babel/preset-flow',
],
plugins: [["#babel/plugin-transform-modules-commonjs"], ["#babel/plugin-proposal-decorators", { "legacy": true }], ["#babel/plugin-proposal-class-properties"]]
}
My solution with "jest": "^28.1.0":
In package.json
under devDependencies add:
"#babel/preset-env": "^7.18.10"
and,
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
},
In babel.config.json add:
{
"presets": ["#babel/preset-env"]
}
You can let Jest do not ignore transforming p-retry by adding this in your jest. config.js, it works for me.
"transformIgnorePatterns": [
"node_modules/(?!(p-retry)/)",
],
In my case I had to add specific module mappings as detailed here: https://stackoverflow.com/a/65250052/285549
This forces Jest to load the CommonJS version of the module since the tests are running in Node even though the eventual target is the browser.

Jest passing tests but --covering option not picking up files

Problem description:
I have written two tests for a typescript class. Those two tests pass so jest successfully retrieves the test files. I then use the --coverage option but it appears jest is not picking the covered files here.
Here is the output I am getting:
api_jester | PASS src/tests/repositories/user.test.ts
api_jester | User Repository
api_jester | ✓ it should return an empty array (18ms)
api_jester | ✓ should successfully create a user and return its data (7ms)
api_jester |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | All files | 0 | 0 | 0 | 0 | |
api_jester | ----------|----------|----------|----------|----------|-------------------|
api_jester | Test Suites: 1 passed, 1 total
api_jester | Tests: 2 passed, 2 total
api_jester | Snapshots: 0 total
api_jester | Time: 3.208s
api_jester | Ran all test suites.
I have tried playing with the collectCoverageFrom option but without any success. I have tested covering with some simple examples found on github and those were working so the problem is not from my environment. I am guessing I somehow missed something in my configuration but I have spend so much time on this I am getting kind of frustrated so maybe some fresh looks could help..
Project architecture :
config
|__ jest.config.js
|__ tsconfig.json
src
|__tests
| |__repositories
| |__user.test.ts
|__repositories
|___ userRepository
|__User.ts
Jest.config.js :
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
package.json
{
"name": "theralog_api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"build": "tsc",
"prettier": "npx prettier --write src/**/*.ts --config ./config/.prettierrc",
"eslint": "npx eslint --config ./config/.eslintrc ./src/**/**/*",
"start:dev": "npx nodemon -L --config ./config/api.nodemon.json",
"test:watch": "npx nodemon -L --config ./config/jester.nodemon.json",
"test:coverage": "npx jest --config ./config/jest.config.js --coverage --colors --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#types/compression": "^1.0.1",
"#types/express": "^4.17.1",
"#types/graphql-depth-limit": "^1.1.2",
"#types/jest": "^24.0.23",
"#types/node": "^12.7.12",
"#typescript-eslint/eslint-plugin": "^2.5.0",
"#typescript-eslint/parser": "^2.5.0",
"apollo-server-testing": "2.9.7",
"babel-jest": "^24.9.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"graphql-depth-limit": "^1.1.0",
"graphql-import": "^0.7.1",
"graphql-import-node": "0.0.4",
"jest": "^24.9.0",
"nodemon": "^1.19.3",
"prettier": "^1.18.2",
"ts-jest": "^24.1.0",
"ts-node": "^8.4.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.2"
},
"dependencies": {
"apollo-server-express": "^2.9.6",
"compression": "^1.7.4",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"graphql": "^14.5.8",
"http": "0.0.0",
"lodash": "^4.17.15",
"ncp": "^2.0.0",
"pg": "^7.12.1",
"winston": "3.2.1"
}
}
jester.nodemon.json
{
"watch": ["../src"],
"ext": "ts",
"exec": "npx jest --config ./config/jest.config.js --watchAll"
}
You are missing a setting in the jest.config.js, collectCoverage: true
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["../src/tests/"],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
collectCoverage: true,
collectCoverageFrom: ["../src/"],
moduleFileExtensions: ["ts", "js", "json"],
coverageDirectory: "../coverage"
};
I also use a more descriptive collectCoverageFrom:
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.interface.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
This way I exclude a number of files I do not want to count coverage from, such as my modules, mocks, and tests.
My full file with the original Jest init process and the comments from that.
For a detailed explanation regarding each configuration property, visit: the Jest documentation
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after the first failure
// bail: false,
// Respect "browser" field in package.json when resolving modules
// browser: false,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\sscott\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls and instances between every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
'!<rootDir>/src/**/*.mock.ts',
'!<rootDir>/src/**/*.module.ts',
'!<rootDir>/src/**/*.spec.ts',
'!<rootDir>/src/**/*.test.ts',
'!<rootDir>/src/**/*.d.ts'
],
// The directory where Jest should output its coverage files
coverageDirectory: "<rootDir>/docs",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"\\\\node_modules\\\\"
],
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: [
"lcov",
"clover",
"text-summary"
],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,
// Make calling deprecated APIs throw helpful error messages
errorOnDeprecated: true,
// Force coverage collection from ignored files usin a array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,
// A set of global variables that need to be available in all test environments
globals: {
"ts-jest": {
"diagnostics": false,
"tsConfig": "tsconfig.json"
}
},
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
moduleFileExtensions: [
"ts",
"tsx",
"js"
],
// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "always",
// A preset that is used as a base for Jest's configuration
// preset: null,
// Run tests from one or more projects
// projects: null,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: null,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: null,
// A list of paths to directories that Jest should use to search for files in
roots: [
"<rootDir>/src"
],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// The path to a module that runs some code to configure or set up the testing framework before each test
// setupTestFrameworkScriptFile: null,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: [
"**/*.spec.ts"
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern Jest uses to detect test files
// testRegex: "",
// This option allows the use of a custom results processor
// testResultsProcessor: null,
// "testResultsProcessor": "jest-jenkins-reporter",
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
transform: {
"^.+\\.(ts|tsx)$": "ts-jest"
},
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
verbose: false
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
After a lot of research at several pages, this worked for me to get the coverage report:
put below line under scripts:
"test:coverage": "set CI=true && react-scripts test --coverage",
And, add below code for jest configuration in package.json file as below:
"jest": {
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/node_modules/**",
"!**/coverage/**",
"!**/serviceWorker.js",
"!**/index.js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"package.json",
"package-lock.json"
]
}
And, then run
npm run test:coverage
Apparently you have to add your source files to roots to make it work. See this PR comment.
Instead of this:
roots: ["../src/tests/"]
Also include your source files:
roots: ["../src/tests/", "../src/repositories/"]
After that and having the correct collectCoverageFrom, all files with 0% coverage were detected as expected.

How can I target node with gulp-babel

I am trying to transpile my coffee code to run mocha tests inside a gulp task.
I get [BABEL] /some/path/example.js: Unknown option: .targets. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.
Here is the relevant section of the gulp task:
.pipe(sourcemaps.init())
.pipe(gulpif(isCoffee, coffee({ bare: true })))
.pipe(babel({ presets: [
'#babel/preset-env', {
targets: {
node: "11.10"
}
}
]
} ))
.pipe(sourcemaps.write('.'))
.pipe(mocha({ reporter: 'list' }));
}
And the dependencies are:
"#babel/cli": "^7.2.3"
"#babel/core": "^7.3.3"
"#babel/preset-env": "^7.3.1"
"#babel/register": "^7.0.0"
...
"gulp": "^4.0.0"
"gulp-babel": "^8.0.0"
...
And the options are documented here .
I think I must have missed a memo somewhere!
Ah ha! This is missing a pair of square brackets: presets should contain an array of arrays, each inner array containing a preset name and optionally a map of options.
[
'preset-name', {
options-key: 'option value'
}
]
]
})).etcetera ```

How to disable webpack dev server auto reload for neutrino project?

Browser: Peruse
Type of project: SAFE network website
I need to turn it off because Peruse considers window.eval() to be a security issue and thus blocks it, which in turn stops my website from loading.
Peruse is the standard browser for Maidsafe as far as I know.
Both of my attempts to fix this have failed:
webpack.config.js
module.exports = {
devServer: {
hot: false,
inline: false
}
};
neutrinorc.js
module.exports = {
use: [
[
'#neutrinojs/vue',
{
html: {
title: 'SAFE Web App'
}
}
],
(neutrino) => {
neutrino.config.devServer
.hot(false)
.inline(false)
}
]
};
The error:
Uncaught Error: Sorry, peruse does not support window.eval().
at window.eval.global.eval (/opt/Maidsafe/Peruse/resources/app.asar/webPreload.js:9:82219)
at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:5000 (http://localhost:5000/index.js:957:1)
at __webpack_require__ (http://localhost:5000/index.js:679:30)
at fn (http://localhost:5000/index.js:89:20)
at Object.0 (http://localhost:5000/index.js:1060:1)
at __webpack_require__ (http://localhost:5000/index.js:679:30)
at http://localhost:5000/index.js:725:37
at http://localhost:5000/index.js:728:10
package.json
...
"dependencies": {
"#babel/helper-module-imports": "^7.0.0-beta.44",
"vue": "^2.5.16"
},
"devDependencies": {
"#neutrinojs/vue": "^8.2.1",
"#vue/devtools": "^4.1.5",
"neutrino": "^8.2.1"
}
...
The eval() errror is not coming from webpack-dev-server.
It turns out that the the default source map mode used by #neutrinojs/web which #neutrinojs/web inherits from is cheap-module-eval-source-map and needs to be set to cheap-module-source-map.
Thus neutrinorc.js needs to be configured as such:
module.exports = {
use: [
['#neutrinojs/vue', {
// Existing options
}],
(neutrino) => {
if (process.env.NODE_ENV === 'development') {
// Override the default development source map of 'cheap-module-eval-source-map'
// to one that doesn't use `eval` (reduces incremental build performance).
neutrino.config.devtool('cheap-module-source-map');
}
}
]
};

Resources