Jasmine / Karma Component Test in Angular 2 Doesn't Work

I am trying to set up testing in my new Angular 2 application (2.0.0-rc.1)

I can run tests that do not use any components defined outside the test file itself (moving the component class inside the test file works)

As soon as I try to execute “new” or use TestComponentBuilder on a component located outside the test file, it explodes.

It seems that querying, fetching and serving both the test file (helloworld.spec.js) and the component file (hello.component2.js)

I saw that this error usually means that what is needed is not loading, but it seems that all files are downloaded.

19 05 2016 08:00:01.319:DEBUG [middleware:source-files]: Requesting /base/demo/hello/helloworld.spec.js /
19 05 2016 08:00:01.319:DEBUG [middleware:source-files]: Fetching D:/web/app/demo/hello/helloworld.spec.js
19 05 2016 08:00:01.320:DEBUG [web-server]: serving (cached): D:/web/app/demo/hello/helloworld.spec.js
19 05 2016 08:00:01.384:DEBUG [middleware:source-files]: Requesting /base/demo/hello/hello.component2.js /
19 05 2016 08:00:01.385:DEBUG [middleware:source-files]: Fetching D:/web/app/demo/hello/hello.component2.js
19 05 2016 08:00:01.386:DEBUG [web-server]: serving (cached): D:/web/app/demo/hello/hello.component2.js
Missing error handler on `socket`.
TypeError: (msg || "").replace is not a function
    at C:\Users\MD\AppData\Roaming\npm\node_modules\karma\lib\reporter.js:45:23
    at onBrowserError (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\lib\reporters\base.js:58:60)
    at null.<anonymous> (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\lib\events.js:13:22)
    at emitTwo (events.js:87:13)
    at emit (events.js:172:7)
    at onKarmaError (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\lib\browser.js:95:13)
    at Socket.<anonymous> (C:\Users\MDn\AppData\Roaming\npm\node_modules\karma\lib\events.js:13:22)
    at emitOne (events.js:82:20)
    at Socket.emit (events.js:169:7)
    at Socket.onevent (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\lib\socket.js:335:8)
    at Socket.onpacket (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\lib\socket.js:295:12)
    at Client.ondecoded (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\lib\client.js:193:14)
    at Decoder.Emitter.emit (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\component-emitter\index.js:134:20)
    at Decoder.add (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io-parser\index.js:247:12)
    at Client.ondata (C:\Users\MD\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\lib\client.js:175:18)

karma.conf

module.exports = function (config) {
  config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    logLevel: config.LOG_DEBUG,
    plugins: [
      require('karma-jasmine'),
      require('karma-coverage'),
      require('karma-chrome-launcher')
    ],
    preprocessors: {
      '**/app/**/!(*spec).js': ['coverage'],
      '**/demo/**/!(*spec).js' : ['coverage']
    },
    coverageReporter: {
      type : 'html',
      dir : 'coverage/',
      includeAllSources: true
    },
    customLaunchers: {
      // chrome setup for travis CI using chromium
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

files: [
  { pattern: 'node_modules/es6-shim/es6-shim.js', included: true, watched: false },
  { pattern: 'node_modules/zone.js/dist/zone.js', included: true, watched: false },
  { pattern: 'node_modules/reflect-metadata/Reflect.js', included: true, watched: false },

  { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: true, watched: false },
  { pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false },
  { pattern: 'node_modules/zone.js/dist/async-test.js', included: true, watched: false },
  { pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: false},

  { pattern: 'node_modules/rxjs/**/*', included: false, watched: false },
  { pattern: 'node_modules/@angular/**/*', included: false, watched: false },
  { pattern: 'karma-test-shim.js', included: true, watched: true },
  { pattern: 'systemjs.config.test.js', included: true, watched: true },

  // Distribution folder.

  { pattern: 'app/**/*', included: false, watched: true },
  { pattern: 'common/**/*', included: false, watched: true },
  { pattern: 'common/utils/**/*', included: false, watched: true },
  { pattern: 'common/utils/logger/**/*', included: false, watched: true },
  { pattern: 'demo/**/*', included: false, watched: true }
],
exclude: [
  // Vendor packages might include spec files. We don't want to use those.
  //'dist/vendor/**/*.spec.js'
],
reporters: ['progress', 'coverage'],
port: 9877,
colors: true,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false


 });
};

karma test-shim.js

/*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

__karma__.loaded = function () {
};

var distPath = '/base/';
var appPath = distPath;

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

function isSpecFile(path) {
  return path.slice(-8) == '.spec.js';
}

function isAppFile(path) {
  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.config({
   baseURL: distPath
});

System.import('systemjs.config.test.js').then(function() {
  // Load and configure the TestComponentBuilder.
  return 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.config.test.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 * Override at the last minute with global.filterSystemConfig (as plunkers do)
 */
(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app/', // 'dist',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular',
    'ng2-bootstrap/ng2-bootstrap' :              'node_modules/ng2-bootstrap/ng2-bootstrap',
    'moment' :                    'node_modules/moment/moment'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'demo':                       {defaultExtension: 'js'},
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',

    '@angular/upgrade'
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  };

  System.config(config);

})(this);

test file

import {
    beforeEachProviders,
    describe,
    expect,
    it,
    inject,
    injectAsync
} from '@angular/core/testing';
import {
    TestComponentBuilder, ComponentFixture
} from '@angular/compiler/testing';
import {HelloAppComponent2} from "./hello.component2";

beforeEachProviders(() => {});

describe('NetX - Hello World App', () => {

    //DOESN'T WORK
    it('should run basic test', () => {
        var myComp = new HelloAppComponent2();
        console.log("HelloWorld Test promise resolved.");
        console.log("Hello World Test");
        expect("HelloWorld").toEqual("HelloWorld");
    });

    /*
        ALSO DOESN'T WORK
     it('should run basic test', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
         return tcb.createAsync(HelloAppComponent2).then((componentFixture: ComponentFixture<any>) => {
             console.log("HelloWorld Test promise resolved.");
             componentFixture.detectChanges();
             console.log("Hello World Test");
             expect("HelloWorld").toEqual("HelloWorld");
         });
     }));
     */

    /*
    THIS TEST BELOW WORKS FINE.
    it('should run basic test', () => {
        console.log("Hello World Test");
        expect("HelloWorld").toEqual("HelloWorld");
    });
    */

});
+4

All Articles