Karma - Jasmine configuration in Aurelia 1 - disconnected after timeout
Asked Answered
L

0

0

For some time, I've been banging my head with running a pretty straightforward (close to a freshly bootstrapped Aurelia project) configuration. I have a problem launching any tests, and the Chrome headless browser gives me a Disconnect each time due to a timeout issue. I have the following config: --> karma.conf.js

const path = require('path');
const project = require('./aurelia_project/aurelia.json');
const tsconfig = require('./tsconfig.json');
const karmaConfig = project.unitTestRunner;

let testSrc = [{ pattern: karmaConfig.source, included: false }, 'test/aurelia-karma.js'];

let output = project.platform.output;
let appSrc = project.build.bundles.map(x => path.join(output, x.name));
let entryIndex = appSrc.indexOf(path.join(output, project.build.loader.configTarget));
let entryBundle = appSrc.splice(entryIndex, 1)[0];
let sourceMaps = [{ pattern: 'scripts/**/*.js.map', included: false }];
let files = [entryBundle].concat(testSrc).concat(appSrc).concat(sourceMaps);

let compilerOptions = tsconfig.compilerOptions;
compilerOptions.inlineSourceMap = true;
compilerOptions.inlineSources = true;

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: [project.testFramework.id],
    files: files,
    exclude: [],
    preprocessors: {
      [karmaConfig.source]: [project.transpiler.id],
      [appSrc]: ['sourcemap', 'coverage']
    },
    typescriptPreprocessor: {
      typescript: require('typescript'),
      options: compilerOptions
    },
    reporters: ['progress', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    /*
     * start these browsers
     * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
     */
    // browsers: [
    //   'Chrome',
    // ],
    /*
     * To run in non-headless mode:
     * 1. Comment the following lines
     * 2. Uncomment the above "browsers" setting
     */
    browsers: ['ChromeHeadless'],
    customLaunchers: {
      ChromeHeadless: {
        base: 'Chrome',
        flags: ['--no-sandbox', '--headless', '--disable-gpu', '--remote-debugging-port=9222']
      }
    },
    /** **************************************************************************** */

    /*
     * Continuous Integration mode
     * if true, Karma captures browsers, runs the tests and exits
     */
    singleRun: true,
    // client.args must be a array of string.
    // Leave 'aurelia-root', project.paths.root in this order so we can find
    // the root of the aurelia project.
    client: {
      args: ['aurelia-root', project.paths.root],
      jasmine: {
        random: false
      }
    },
    coverageReporter: {
      reporters: [{ type: 'html' }, { type: 'lcovonly' }, { type: 'text-summary' }],
      dir: path.resolve(__dirname, 'test/coverage-karma'),
      subdir: '.'
    }
  });
};

--> ./test/aurelia.karma.js

(function (global) {
  var karma = global.__karma__;
  var requirejs = global.requirejs;
  var locationPathname = global.location.pathname;
  var root = 'src';
  karma.config.args.forEach(function (value, index) {
    if (value === 'aurelia-root') {
      root = karma.config.args[index + 1];
    }
  });

  if (!karma || !requirejs) {
    return;
  }

  function normalizePath(path) {
    var normalized = [];
    var parts = path
      .split('?')[0] // cut off GET params, used by noext requirejs plugin
      .split('/');

    for (var i = 0; i < parts.length; i++) {
      if (parts[i] === '.') {
        continue;
      }

      if (parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..') {
        normalized.pop();
        continue;
      }

      normalized.push(parts[i]);
    }

    // Use case of testing source code. RequireJS doesn't add .js extension to files asked via sibling selector
    // If normalized path doesn't include some type of extension, add the .js to it
    if (normalized.length > 0 && normalized[normalized.length - 1].indexOf('.') < 0) {
      normalized[normalized.length - 1] = normalized[normalized.length - 1] + '.js';
    }

    return normalized.join('/');
  }

  function patchRequireJS(files, originalLoadFn, locationPathname) {
    var IS_DEBUG = /debug\.html$/.test(locationPathname);

    requirejs.load = function (context, moduleName, url) {
      url = normalizePath(url);

      if (files.hasOwnProperty(url) && !IS_DEBUG) {
        url = url + '?' + files[url];
      }

      if (url.indexOf('/base') !== 0) {
        url = '/base/' + url;
      }

      return originalLoadFn.call(this, context, moduleName, url);
    };

    var originalDefine = global.define;
    global.define = function (name, deps, m) {
      if (typeof name === 'string') {
        // alias from module "/base/root/name" to module "name"
        originalDefine('/base/' + root + '/' + name, [name], function (result) {
          return result;
        });
      }

      // normal module define("name")
      return originalDefine(name, deps, m);
    };
    global.define.amd = originalDefine.amd;
  }

  function requireTests() {
    var TEST_REGEXP = /(spec)\.js$/i;
    var allTestFiles = [];

    Object.keys(window.__karma__.files).forEach(function (file) {
      if (TEST_REGEXP.test(file)) {
        allTestFiles.push(file);
      }
    });

    require(['/base/test/unit/setup.js'], function () {
      require(allTestFiles, window.__karma__.start);
    });
  }

  karma.loaded = function () {}; // make it async
  patchRequireJS(karma.files, requirejs.load, locationPathname);
  requireTests();
})(window);

---> tsconfig.json

{
  "compileOnSave": false,
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true,
  "compilerOptions": {
    "module": "amd",
    "noImplicitAny": false,
    "declaration": true,
    "typeRoots": [
      "./node_modules/@types"
    ],
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "target": "es5",
    "lib": [
      "es2015",
      "dom"
    ],
    "moduleResolution": "node",
    "baseUrl": "src",
    "resolveJsonModule": true,
    "paths": {
      "resources": [
        ""
      ]
    },
    "allowJs": false
  },
  "include": [
    "./src/**/*.ts",
    "./dev-app/**/*.ts",
    "./test/**/*.ts",
    "./types/**/*.d.ts"
  ],
  "atom": {
    "rewriteTsconfig": false
  }
}

---> ./test/unit/setup.js

import 'aurelia-polyfills';
import { initialize } from 'aurelia-pal-browser';

initialize();

And, I'm getting this all the time

I really can't understand what is wrong here as the Karma is not so explicit on errors. I see no Chrome launching, and no tests are connecting. If you experienced this issue before or have a clue how to solve it - I'll be extremely thankful.

p.s. My tests are *.spec.ts in ./test/unit folder.

Lycanthropy answered 8/3 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.