使用 NgUpgrade 启动 Karma 的意外拒绝

Unexpected Rejections upon Karma Start up with NgUpgrade

我正在将 ngupgrade 集成到我们的 AngularJS 应用程序中,但在加载 Karma 时我不断收到这些意外的拒绝错误。

我的应用程序在 ngupgrade 上运行良好,只是单元测试有这个问题。

幸运的是,这不会破坏 PhantomJS 中的单元测试,但在 Chrome 中会。

我尝试浏览应用程序并将 try-catch 块添加到我的所有承诺中。我能够删除其中一个,但不幸的是,仅此而已。

这是我的 Karma 配置...

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 typescript@3.4.3 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

提前致谢!鼓励和赞赏任何提示或技巧!

我可以通过检查 window 的 Karma 对象来阻止这个未处理的拒绝。

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