Как мне исключить "node_modules" из моего покрытия кода? - PullRequest
1 голос
/ 08 мая 2020
• 1000

(TypeScript -> Gulp, Browserify, Babel -> Javascript -> Cypress)

Когда я запускаю свои кипарисовые тесты, процент покрытия кода неверен, потому что он включает каталог node_modules. Все, что я хочу сделать, это исключить node_modules из моего покрытия кода, чтобы покрытие было неправильным .

Я запускаю команду npm run test:coverage (см. Мой пакет json ниже) для выполнения всех необходимых шагов.

tsconfig.json

{
    "compilerOptions": {
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "lib": ["dom", "es5", "es6", "es2017", "es2018", "es2020"],  /* Specify library files to be included in the compilation. */
        "allowJs": false,                         /* Allow javascript files to be compiled. */
        "checkJs": false,                         /* Report errors in .js files. */
        "jsx": "react",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        "sourceMap": true,                        /* Generates corresponding '.map' file. */
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
        "outDir": "docs",                         /* Redirect output structure to the directory. */
        "rootDir": "src",                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        "removeComments": true,                   /* Do not emit comments to output. */
        // "noEmit": true,                        /* Do not emit outputs. */
        // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
        "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        "noImplicitAny": true,                    /* Raise error on expressions and declarations with an implied 'any' type. */
        "strictNullChecks": true,                 /* Enable strict null checks. */
        "strictFunctionTypes": true,              /* Enable strict checking of function types. */
        "strictBindCallApply": true,              /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        "strictPropertyInitialization": true,     /* Enable strict checking of property initialization in classes. */
        "noImplicitThis": true,                   /* Raise error on 'this' expressions with an implied 'any' type. */
        "alwaysStrict": true,                     /* Parse in strict mode and emit "use strict" for each source file. */

        /* Additional Checks */
        "noUnusedLocals": true,                   /* Report errors on unused locals. */
        "noUnusedParameters": true,               /* Report errors on unused parameters. */
        "noImplicitReturns": true,                /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true,       /* Report errors for fallthrough cases in switch statement. */

        /* Module Resolution Options */
        "moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
        // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
        // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
        // "typeRoots": [],                       /* List of folders to include type definitions from. */
        // "types": [],                           /* Type declaration files to be included in compilation. */
        "allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

        /* Experimental Options */
        "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

        /* Advanced Options */
        "resolveJsonModule": true,                /* Include modules imported with '.json' extension */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
    },
    "exclude": [
        "dist",
        "docs",
        "gulpfile.js",
        "node_modules"
    ]
}

package.json

{
    "name": "webdntd",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
        "build": "gulp",
        "watch": "gulp watch",
        "instrument": "gulp instrument",
        "test": "cypress run --config-file cypress.json",
        "test:ci": "npm run test",
        "test:local": "cypress run --config-file cypressDev.json",
        "test:coverage": "npm run instrument && npm run test:local && npm run badges",
        "badges": "make-coverage-badge --report-path './coverage/coverage-summary.json' --output-path './docs/static/coverage_badge.svg'"
    },
    "dependencies": {
        "js-cookie": "^2.2.1",
        "mithril": "^2.0.4"
    },
    "devDependencies": {
        "@babel/core": "^7.9.6",
        "@babel/preset-env": "^7.9.6",
        "@cypress/code-coverage": "^3.7.0",
        "@types/dom-inputevent": "^1.0.5",
        "@types/gapi": "0.0.39",
        "@types/gapi.auth2": "0.0.51",
        "@types/gapi.client": "^1.0.1",
        "@types/gapi.client.sheets": "^4.0.3",
        "@types/js-cookie": "^2.2.5",
        "@types/mithril": "^2.0.2",
        "babel-plugin-istanbul": "^6.0.0",
        "browserify": "^16.5.1",
        "cypress": "^4.5.0",
        "gulp": "^4.0.2",
        "gulp-babel": "^8.0.0",
        "gulp-cli": "^2.2.0",
        "gulp-sourcemaps": "^2.6.5",
        "gulp-uglify": "^3.0.2",
        "istanbul-lib-coverage": "^3.0.0",
        "make-coverage-badge": "^1.2.0",
        "nyc": "^15.0.1",
        "tsc-watch": "^4.2.3",
        "tsify": "^4.0.1",
        "typescript": "^3.8.3",
        "vinyl-buffer": "^1.0.1",
        "vinyl-source-stream": "^2.0.0",
        "webpack": "^4.42.1",
        "webpack-cli": "^3.3.11"
    }
}

gulpfile.js

const gulp = require('gulp')
const tsify = require('tsify')
const babel = require("gulp-babel")
const uglify = require('gulp-uglify')
const buffer = require('vinyl-buffer')
const browserify = require('browserify')
const source = require('vinyl-source-stream')
const sourcemaps = require('gulp-sourcemaps')

const options = {
    "input": {
        "ts": ["./src/**/*.ts"]
    },
    "output": {
        "bundle": "dntd.js",
        "js": "./docs",
        "sourcemap": "./"
    },
    "babel": {
        presets: [
            "@babel/preset-env"
        ],
        plugins: [
            ["istanbul", { exclude: 'node_modules' }]
        ]
    },
    "browserify": {
        basedir: ".",
        debug: true,
        entries: ["./src/index.ts"],
        cache: {},
        packageCache: {}
    }
}


function js() {
    return browserify(options.browserify)
        .plugin(tsify)
        .bundle()
        .pipe(source(options.output.bundle))
        .pipe(buffer())
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(sourcemaps.write(options.output.sourcemap))
        .pipe(gulp.dest(options.output.js))
}

function jsi() {
    return browserify(options.browserify)
        .plugin(tsify)
        .bundle()
        .pipe(source(options.output.bundle))
        .pipe(buffer())
        .pipe(sourcemaps.init())
        .pipe(babel(options.babel))
        .pipe(sourcemaps.write(options.output.sourcemap))
        .pipe(gulp.dest(options.output.js))
}

gulp.task("default", js)
gulp.task("watch", gulp.series(js, watchTs = () => { gulp.watch(options.input.ts, js) }))
gulp.task("instrument", jsi)

Каталог

.
├── coverage
├── cypress
├── cypress.json
├── cypressDev.json
├── docs
│  ├── dntd.js
│  ├── dntd.js.map
│  ├── index.html
│  └── static
│     ├── coverage_badge.svg
├── gulpfile.js
├── node_modules
├── package-lock.json
├── package.json
├── README.md
├── src
│  ├── classes
│  │  └── ...
│  ├── components
│  │  └── ...
│  ├── helpers
│  │  └── ...
│  ├── index.ts
│  └── mocks
│     └── ...
├── tsconfig.json

Вывод отчета о покрытии Coverage Report Output

NY C Вывод

npx nyc report
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |       0 |        0 |       0 |       0 |                   
----------|---------|----------|---------|---------|-------------------
...