karma-runner / karma-coverage

A Karma plugin. Generate code coverage.
MIT License
770 stars 247 forks source link

TypeError: (msg || "").replace is not a function #233

Open HeavenlyHost opened 8 years ago

HeavenlyHost commented 8 years ago

Can someone explain to me what I am doing wrong with the karma coverage. I am currently developing an angular 2 (RC1) service in typescript and want to not only run unit tests on it but also provide code coverage reports. If running the tests without the coverage reporter all is good and the tests are run. Unfortunately, when I include the coverage reporter karma bails with the following error...

10 06 2016 10:45:49.583:DEBUG [web-server]: serving (cached): D:/Git/@my-namespace/my-service/node_modules/rxjs/scheduler/FutureAction.js Missing error handler on socket. TypeError: (msg || "").replace is not a function at D:\Git\@my-namespace\my-service\node_modules\karma\lib\reporter.js:45:23

What I am doing is building typescript into a folder called dist and then exposing this to karma test and coverage

details are below...

... any ideas...?

Expected behavior

karma should run tests and create a coverage file

Actual behavior

10 06 2016 10:45:49.583:DEBUG [web-server]: serving (cached): D:/Git/@my-namespace/my-service/node_modules/rxjs/scheduler/FutureAction.js Missing error handler on socket. TypeError: (msg || "").replace is not a function at D:\Git\@my-namespace\my-service\node_modules\karma\lib\reporter.js:45:23

Enviroment Details

Typescript: 1.8.10 Karma version: 0.13.22 Karma coverage: 0.5.5

karma.config.js

module.exports = function(config) {

    // transpiled app JS files
    var appBase   = "dist/";

    // component assets fetched by Angular's compiler
    var appAssets ="/base/dist/";

    config.set({
        autoWatch: true,
        basePath: ".",
        browserNoActivityTimeout: 20000,
        browsers: ["Chrome"],
        colors: true,
        exclude: [
             "node_modules/**/*.spec.js"
        ],
        files: [
            // Standard libs
            "node_modules/systemjs/dist/system-polyfills.js",
            "node_modules/systemjs/dist/system.src.js",
            "node_modules/es6-shim/es6-shim.js",
            "node_modules/reflect-metadata/Reflect.js",
            "node_modules/zone.js/dist/zone.js",
            "node_modules/zone.js/dist/jasmine-patch.js",
            "node_modules/zone.js/dist/async-test.js",
            "node_modules/zone.js/dist/fake-async-test.js",

            // Standard libs with custom patterns
            {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false},,
            {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false},

            // Custom shim
            "karma-test-shim.js",

            // Transpiled application & spec code paths loaded via module imports
            {pattern: 'dist/**/*.js', included: false, watched: true},
            {pattern: 'dist/**/*.js.map', included: false, watched: false}
        ],
        frameworks: ["jasmine"],
        logLevel: config.LOG_DEBUG,
        plugins: [
            "karma-jasmine",
            "karma-chrome-launcher",
            "karma-coverage"
        ],
        port: 9876,
        preprocessors: {
            // source files, that you wanna generate coverage for
            // do not include tests or libraries
            // (these files will be instrumented by Istanbul)      
            "dist/**/!(*spec).js": ["coverage"]
        },
        proxies: {
            // proxied base paths for loading assets
            // required for component assets fetched by Angular's compiler
            "/dist/": appAssets
        },
        reporters: ["progress", "dots", "coverage"],
        singleRun: true,
    });
 }
markballenger commented 8 years ago

i am battling the same confusing problem...

Kavorka79 commented 8 years ago

I have the same issue. I must remove the preprocessor step to make test run.

Appeared when I upgraded to angular rc4 from beta-9. I don't know why or if it's some related library to angular that is the problem.

Any thoughts @karma-runner

dignifiedquire commented 8 years ago

This error message means something in your config, or your code is throwing an error. (I know the error message is not super helpful :/)

HeavenlyHost commented 8 years ago

@dignifiedquire that just seems like a cop out, the problem does not appear to be with code, the error message is within some socket library to do with either karma or angular. If this is not true then please enlighten us with an example 😐

maksimr commented 8 years ago

@HeavenlyHost could you please set console.log here \node_modules\karma\lib\reporter.js:45:23 and watch what is msg

Thanks

Kavorka79 commented 8 years ago

Thanks for your reply! :-)

I have tested with julemr test seed project and then it works so you are correct that something in our setup is wrong, maybe you can spot what it is.

Here is my files

package.json

{
  "name": "pixie",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "ag-grid": "5.0.0-alpha.0",
    "ag-grid-ng2": "5.0.0-alpha.0",
    "core-js": "^2.4.0",
    "es6-promise": "3.1.2",
    "es6-shim": "0.34.1",
    "foundation-sites": "6.2.1",
    "ng2-i18next": "0.1.6",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.6",
    "systemjs": "0.19.24",
    "zone.js": "^0.6.12"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "del": "^2.2.0",
    "gulp": "^3.9.1",
    "gulp-load-plugins": "^1.2.0",
    "gulp-sass": "^2.3.1",
    "gulp-sourcemaps": "2.0.0-alpha",
    "gulp-task-listing": "^1.0.1",
    "gulp-tslint": "^4.3.3",
    "gulp-typescript": "2.13.5",
    "gulp-watch": "^4.3.5",
    "jasmine-core": "2.4.1",
    "karma": "0.13.22",
    "karma-chrome-launcher": "1.0.1",
    "karma-coverage": "1.0.0",
    "karma-htmlfile-reporter": "0.3.4",
    "karma-jasmine": "1.0.2",
    "karma-spec-reporter": "0.0.26",
    "karma-teamcity-reporter": "1.0.0",
    "lite-server": "^2.1.0",
    "lodash": "^4.5.1",
    "remap-istanbul": "Kavorka79/remap-istanbul",
    "rimraf": "^2.5.2",
    "run-sequence": "1.2.1",
    "tslint": "3.10.2",
    "typescript": "^1.8.10",
    "typings": "0.8.0"
  }
}

Karma.conf.js

// Karma configuration
// Generated on Thu Mar 03 2016 17:01:08 GMT+0100 (Västeuropa, normaltid)

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["jasmine"],

        // list of files / patterns to load in the browser
        files: [
            // Polyfills.
            "wwwroot/libs/es6-shim/es6-shim.js",
            "wwwroot/libs/reflect-metadata/Reflect.js",

            // System.js for module loading
            "wwwroot/libs/systemjs/dist/system.src.js",
            "wwwroot/libs/systemjs/dist/system-polyfills.js",

            // Zone.js dependencies
            "wwwroot/libs/zone.js/dist/zone.js",
            "wwwroot/libs/zone.js/dist/jasmine-patch.js",
            "wwwroot/libs/zone.js/dist/async-test.js",
            "wwwroot/libs/zone.js/dist/fake-async-test.js",

            // RxJs.
            { pattern: "wwwroot/libs/rxjs/**/*.js", included: false, watched: false },
            { pattern: "wwwroot/libs/rxjs/**/*.js.map", included: false, watched: false },

            { pattern: "karma-test-shim.js", included: true, watched: true },

            // Angular
            { pattern: "wwwroot/libs/@angular/**/*.js", included: false, watched: true },
            { pattern: "wwwroot/libs/@angular/**/*.js.map", included: false, watched: true },

            // Application code
            { pattern: "wwwroot/app/**/*.js", included: false, watched: true },

            // Configuration
            { pattern: "wwwroot/config/**/*.js", included: false, watched: true },

            // Paths loaded via Angular's component compiler
            // (these paths need to be rewritten, see proxies section)
            { pattern: "wwwroot/app/**/*.html", included: false, watched: true },

            // Paths to support debugging with source maps in dev tools
            //{ pattern: "app/**/*.ts", included: false, watched: false },
            { pattern: "wwwroot/app/**/*.js.map", included: false, watched: false }
        ],

        // list of files to exclude
        exclude: [
        ],

        // proxied base paths
        proxies:
        {
            // required for component assests fetched by Angular's compiler
            "/app/": "/base/wwwroot/app/"
        },

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "wwwroot/app/**/!(*spec).js": "coverage"
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["spec", "html", "coverage"],

        // default reporter configuration.
        specReporter: {
            maxLogLines: 5, // limit number of lines logged per test 
            suppressErrorSummary: true, // do not print error summary 
            suppressFailed: false, // do not print information about failed tests 
            suppressPassed: true, // do not print information about passed tests 
            suppressSkipped: true, // do not print information about skipped tests 
            showSpecTiming: false // print the time elapsed for each spec 
        },
        //htmlReporter: { //karma-html-reporter
        //    outputDir: "reports/specs/", // where to put the reports  
        //    templatePath: null, // set if you moved jasmine_template.html 
        //    focusOnFailures: true, // reports show failures on start 
        //    namedFiles: false, // name files instead of creating sub-directories 
        //    pageTitle: "Pixie spec report", // page title for reports; browser info by default 
        //    urlFriendlyName: false, // simply replaces spaces with _ for files/dirs 
        //    reportName: "html", // report summary filename; browser info by default 

        //    // experimental 
        //    preserveDescribeNesting: true, // folded suites stay folded  
        //    foldAll: true // reports start folded (only with preserveDescribeNesting) 
        //},
        htmlReporter: { //karma-htmlfile-reporter
            outputFile: "reports/specs/html/index.html",

            // Optional 
            pageTitle: "Pixie spec reports",
            subPageTitle: "A sample project description",
            groupSuites: true,
            useCompactStyle: true,
            useLegacyStyle: false
        },
        coverageReporter:
        {
            includeAllSources: true,
            type: "json",
            dir: "reports/coverage",
            subdir: "json",
            file: "coverage-final.json",
            instrumenterOptions: {
                istanbul: { noCompact: true }
            }
        },

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ["Chrome"],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
}

Karma-test-shim.js

// Turn on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};

function isJsFile(path) {
    return path.slice(-3) == ".js";
}

function isSpecFile(path) {
    return /\.spec\.js$/.test(path);
}

function isAppFile(path) {
    var appPath = "/base/wwwroot/app/";
    return isJsFile(path) && (path.substr(0, appPath.length) == appPath);
}

var allSpecFiles = Object.keys(window.__karma__.files)
    .filter(isSpecFile)
    .filter(isAppFile);

// Load our SystemJS configuration.
System.packageWithIndex = true; //used in systemjs.config.js

System.config({
    baseURL: "/base/wwwroot"
});

System.import("config/systemjs.config.js")
    .then(function() {
        Promise.all([
                System.import("@angular/core/testing"),
                System.import("@angular/platform-browser-dynamic/testing")
            ])
            .then(function (providers) {
                var testing = providers[0];
                var testingBrowser = providers[1];

                testing.setBaseTestProviders(testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
                    testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
            })
            .then(function() {
                // Finally, load all spec files.
                // This will run the tests directly.
                return Promise.all(
                    allSpecFiles.map(function(moduleName) {
                        return System.import(moduleName);
                    }));
            })
            .then(__karma__.start, __karma__.error);
    });

systemjs.conf.js

(function (global) {

    /**
     * User mappings
     */

    var usermap = {
        'ag-grid-ng2': "ag-grid-ng2",
        'ag-grid': "ag-grid",
        'ng2-i18next': "libs/ng2-i18next",
        'i18next': "libs/i18next/i18next.js",
        'i18nextXHRBackend': "libs/i18next-xhr-backend/i18nextXHRBackend.js",
        'i18nextBrowserLanguageDetector': "libs/i18next-browser-languagedetector/i18nextBrowserLanguageDetector.js"
    }

    var userpackages = {
        'ag-grid-ng2': { defaultExtension: "js" },
        'ag-grid': { defaultExtension: "js" },
        'ng2-i18next': { format: "cjs", defaultExtension: "js" },
        'i18next': { format: "global" },
        'i18nextXHRBackend': { format: "global" },
        'i18nextBrowserLanguageDetector': { format: "global" }
    }

    /**
     * Angular specific
     */
    var map = {
        '@angular': "libs/@angular",
        'angular2-in-memory-web-api': "libs/angular2-in-memory-web-api",
        'rxjs': "libs/rxjs",
        'app': "app"
    };

    var packages = {
        'app': { defaultExtension: "js" },
        'rxjs': { defaultExtension: "js" },
        'angular2-in-memory-web-api': { main: "index.js", defaultExtension: "js" }
    };

    var ngPackageNames = [
        "common",
        "compiler",
        "core",
        "forms",
        "http",
        "platform-browser",
        "platform-browser-dynamic",
        "router",
        "router-deprecated",
        "upgrade"
    ];

    // Individual files (~300 requests):
    function packIndex(pkgName) {
        packages[`@angular/${pkgName}`] = { main: "index.js", defaultExtension: "js" };
    }
    // Bundled (~40 requests):
    function packUmd(pkgName) {
        packages[`@angular/${pkgName}`] = { main: `/bundles/${pkgName}.umd.js`, defaultExtension: "js" };
    }

    // Most environments should use UMD; some (Karma) need the individual index files
    var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;

    // Add package entries for angular packages
    ngPackageNames.forEach(setPackageConfig);

    //Apply Angular specific config
    System.config({ map: map, packages: packages });

    //Apply user specific config
    System.config({ map: usermap, packages: userpackages });
})(this);
Cayan commented 8 years ago

I'm also experiencing the same issue.

It seems to happen only when I create a test for an angular2@rc5 component that requires a provider. I'm still figuring out how to inject those.

@maksimr in my case the console.log(msg) from node_modules/karma/lib/reporter.js:45 is: { originalErr: {} }