Search code examples
angularjsangularkarma-runnerkarma-webpackng-upgrade

Unexpected Rejections upon Karma Start up with NgUpgrade


I'm in the process of integrating ngupgrade into our AngularJS app and I keep getting these unexpected rejection errors when Karma is loading up.

My app is working fine with ngupgrade it's just the unit tests that are having this problem.

Luckily this doesn't break the unit tests in PhantomJS but in Chrome it does.

I tried going through the app and adding try-catch blocks to all of my promises. I was able to remove one of these but unfortunately, that's it.

Here are my Karma configurations...

var path = require("path");
var webpackConfig = require("../../webpack.config");
webpackConfig.resolve = webpackConfig.resolve || {};
webpackConfig.resolve.modules = webpackConfig.resolve.modules || [];
webpackConfig.resolve.modules.push("node_modules");

//The tests are not minification safe, remove the uglify plugin.
webpackConfig.plugins.some(function(plugin, index) {
    if (plugin.constructor.name === "UglifyJsPlugin") {
        webpackConfig.plugins.splice(index, 1);
        return true;
    }
});
/* Removing the chunks plugin */
webpackConfig.plugins.some(function(plugin, index) {
    if (plugin.constructor.name === "CommonsChunkPlugin") {
        webpackConfig.plugins.splice(index, 1);
        return true;
    }
});

webpackConfig.module.rules.push({
    test: /\.[tj]+sx?$/,
    loader: "istanbul-instrumenter-loader",
    exclude: [/(node_modules|bower_components)/, "app/**/*.spec.ts"],
    enforce: "post",
    options: {
        esModules: true
    }
});

var entry = path.resolve(webpackConfig.context, webpackConfig.entry.app);
webpackConfig.entry = null; //karma-webpack cannot handle multiple entry points. https://github.com/webpack-contrib/karma-webpack/issues/231
var preprocessors = {};
preprocessors[entry] = ["webpack", "coverage", "sourcemap"];

preprocessors["karmaTestIndex.js"] = ["webpack"];

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"],

        webpack: webpackConfig,
        webpackMiddleware: {
            stats: "errors-only",
            noInfo: true,
            logLevel: "error"
        },

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: preprocessors,

        // list of files / patterns to load in the browser
        files: [
            //With Typescript and imports, we no longer have to load these deps in IBWC
            //we do in SAS because they are marked as externals.
            entry,

            "node_modules/angular-mocks/angular-mocks.js",
            "test/karma/globalMocks.js",

            // NEW CONFIGURATION FOR SINGLE-BUNDLING
            "karmaTestIndex.js"

            // OLD CONFIGURATION FOR MULTI-BUNDLING
            // "app/**/*.spec.ts"
        ],
        mime: { "text/x-typescript": ["ts", "tsx"] },

        // list of files to exclude
        exclude: ["test/karma/**/*conf.js", "target/**/*.min.js"],

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

        // the default configuration
        junitReporter: {
            outputDir: "target/testResults",
            outputFile: "test-results.xml"
        },

        coverageIstanbulReporter: {
            // reports can be any that are listed here: https://github.com/istanbuljs/istanbul-reports/tree/590e6b0089f67b723a1fdf57bc7ccc080ff189d7/lib
            reports: ["html", "cobertura", "text-summary"],

            // base output directory. If you include %browser% in the path it will be replaced with the karma browser name
            dir: "target/testResults/coverage/",

            // if using webpack and pre-loaders, work around webpack breaking the source path
            fixWebpackSourcePaths: true,

            // stop istanbul outputting messages like `File [${filename}] ignored, nothing could be mapped`
            skipFilesWithNoCoverage: true,

            // Most reporters accept additional config options. You can pass these through the `report-config` option
            "report-config": {
                // all options available at: https://github.com/istanbuljs/istanbul-reports/blob/590e6b0089f67b723a1fdf57bc7ccc080ff189d7/lib/html/index.js#L135-L137
                html: {
                    // outputs the report in ./coverage/html
                    subdir: "html"
                }
            },

            // enforce percentage thresholds
            // anything under these percentages will cause karma to fail with an exit code of 1 if not running in watch mode
            thresholds: {
                statements: 1,
                lines: 1,
                branches: 1,
                functions: 1
            }
        },

        // 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_ERROR,

        // 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'],
        browsers: ["PhantomJS"],

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

        // https://github.com/jasmine/jasmine/issues/1413#issuecomment-334247097
        // Adding these timeouts to handle Windows timeout issues with Karma.
        captureTimeout: 210000,
        browserDisconnectTolerance: 3,
        browserDisconnectTimeout: 210000,
        browserNoActivityTimeout: 210000
    });
};

[16:40:03] Using gulpfile ~/githubEnterprise/onlineBanking/consumer-online-banking-web-client/gulpfile.js

[16:40:03] Starting 'unit_test'...

ts-loader: Using [email protected] and /Users/kevinlogan/githubEnterprise/myapp/tsconfig.json

Webpack Bundle Analyzer saved report to /Users/kevinlogan/githubEnterprise/myapp/target/testResults/bundleReport.html

PhantomJS 2.1.1 (Mac OS X 0.0.0) LOG: 'WARNING: Tried to load AngularJS more than once.'

PhantomJS 2.1.1 (Mac OS X 0.0.0) LOG: 'WARNING: Tried to load AngularJS more than once.'

..

ERROR: Object{data: 'NOT FOUND', status: 404, headers: function (name) { ... }, config: Object{method: 'GET', transformRequest: [...], transformResponse: [...], paramSerializer: function ngParamSerializer(params) { ... }, jsonpCallbackParam: 'callback', url: '../apps/ib/shared/json/stringResources.json?time=1569012069658', headers: Object{Accept: ...}}, statusText: 'Not Found', xhrStatus: 'complete'}

ERROR: Object{data: 'NOT FOUND', status: 404, headers: function (name) { ... }, config: Object{method: 'GET', transformRequest: [...], transformResponse: [...], paramSerializer: function ngParamSerializer(params) { ... }, jsonpCallbackParam: 'callback', url: '../apps/ib/shared/json/stringResources.json?time=1569012069658', headers: Object{Accept: ...}}, statusText: 'Not Found', xhrStatus: 'complete'}

ERROR: Object{data: 'NOT FOUND', status: 404, headers: function (name) { ... }, config: Object{method: 'DELETE', transformRequest: [...], transformResponse: [...], paramSerializer: function ngParamSerializer(params) { ... }, jsonpCallbackParam: 'callback', headers: Object{X-Device-Fingerprint: ..., X-Platform: ..., X-Device-UID: ..., X-Platform-Version: ..., X-Client-Version: ..., X-Manufacturer: ..., X-Model: ..., X-Carrier: ..., X-Resolution-Height: ..., X-Resolution-Width: ..., Accept: ...}, url: '../mobile/v1/auth/logout'}, statusText: 'Not Found', xhrStatus: 'complete'}

ERROR: Object{data: 'NOT FOUND', status: 404, headers: function (name) { ... }, config: Object{method: 'DELETE', transformRequest: [...], transformResponse: [...], paramSerializer: function ngParamSerializer(params) { ... }, jsonpCallbackParam: 'callback', headers: Object{X-Device-Fingerprint: ..., X-Platform: ..., X-Device-UID: ..., X-Platform-Version: ..., X-Client-Version: ..., X-Manufacturer: ..., X-Model: ..., X-Carrier: ..., X-Resolution-Height: ..., X-Resolution-Width: ..., Accept: ...}, url: '../mobile/v1/auth/logout'}, statusText: 'Not Found', xhrStatus: 'complete'}

ERROR: 'Possibly unhandled rejection: {"data":"NOT FOUND","status":404,"config":{"method":"DELETE","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"X-Device-Fingerprint":"version=2&pm_fpua=mozilla/5.0 (macintosh; intel mac os x) applewebkit/538.1 (khtml, like gecko) phantomjs/2.1.1 safari/538.1|5.0 (Macintosh; Intel Mac OS X) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1|MacIntel&pm_fpsc=32|1024|768|768&pm_fpsw=&pm_fptz=-4&pm_fpln=lang=en-US|syslang=|userlang=&pm_fpjv=0&pm_fpco=1&pm_fpasw=&pm_fpan=Netscape&pm_fpacn=Mozilla&pm_fpol=true&pm_fposp=&pm_fpup=&pm_fpsaw=1024&pm_fpspd=32&pm_fpsbd=&pm_fpsdx=&pm_fpsdy=&pm_fpslx=&pm_fpsly=&pm_fpsfse=&pm_fpsui=","X-Platform":"Web","X-Device-UID":"75b3c787-3ca4-41b8-ac3b-04a8ae495ed7","X-Platform-Version":"2.1.1","X-Client-Version":"3.37","X-Manufacturer":{"architecture":32,"family":"OS X","version":null},"X-Model":"PhantomJS","X-Carrier":"Unknown","X-Resolution-Height":768,"X-Resolution-Width":1024,"Accept":"application/json, text/plain, */*"},"url":"../mobile/v1/auth/logout"},"statusText":"Not Found","xhrStatus":"complete","resource":{}}'

ERROR: 'Possibly unhandled rejection: {"data":"NOT FOUND","status":404,"config":{"method":"DELETE","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"X-Device-Fingerprint":"version=2&pm_fpua=mozilla/5.0 (macintosh; intel mac os x) applewebkit/538.1 (khtml, like gecko) phantomjs/2.1.1 safari/538.1|5.0 (Macintosh; Intel Mac OS X) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1|MacIntel&pm_fpsc=32|1024|768|768&pm_fpsw=&pm_fptz=-4&pm_fpln=lang=en-US|syslang=|userlang=&pm_fpjv=0&pm_fpco=1&pm_fpasw=&pm_fpan=Netscape&pm_fpacn=Mozilla&pm_fpol=true&pm_fposp=&pm_fpup=&pm_fpsaw=1024&pm_fpspd=32&pm_fpsbd=&pm_fpsdx=&pm_fpsdy=&pm_fpslx=&pm_fpsly=&pm_fpsfse=&pm_fpsui=","X-Platform":"Web","X-Device-UID":"75b3c787-3ca4-41b8-ac3b-04a8ae495ed7","X-Platform-Version":"2.1.1","X-Client-Version":"3.37","X-Manufacturer":{"architecture":32,"family":"OS X","version":null},"X-Model":"PhantomJS","X-Carrier":"Unknown","X-Resolution-Height":768,"X-Resolution-Width":1024,"Accept":"application/json, text/plain, */*"},"url":"../mobile/v1/auth/logout"},"statusText":"Not Found","xhrStatus":"complete","resource":{}}'

................................................................................

................................................................................

................................................................................

................................

PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 274 of 363 (skipped 89) SUCCESS (27.358 secs / 26.02 secs)

TOTAL: 274 SUCCESS

Thank you in advance! Any tips or tricks are encouraged and appreciated!


Solution

  • I was able to stop this unhandled rejection by checking the window's object for Karma.

    if(!(window as any).__karma__) {
      // perform promise
    } else {
      this.result = {status: "success"};
    }