jeudi 29 octobre 2015

Angular 2 unit tests with Karma

I learn Angular 2 and now try to do some unit tests using Karma. I configured my project base on this article http://ift.tt/1O9xpDB but when I'm running unit tests I got below error:

WARN [web-server]: 404: /base/src/angular2/angular2 Error: XHR error (404 Not Found) loading http://localhost:9876/base/src/angular2/angular2

I have gulp tasks which compiles my ts files into javascript.

karma.conf.js

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: http://ift.tt/1ft83uu
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    // list of files / patterns to load in the browser
    files: [
        'node_modules/traceur/bin/traceur-runtime.js',
        { pattern: 'src/build/**/*.js', included: false, serve: true },
        'node_modules/es6-module-loader/dist/es6-module-loader.js',
        'node_modules/systemjs/dist/system.js',
        'node_modules/angular2/bundles/angular2.dev.js',
        'test-main.js',
        {
            pattern: 'src/test/**/*spec.js',
            included: false,
            serve: true,
            watch: true
        }
    ],


    // list of files to exclude
    exclude: [
        'src/build/app.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: http://ift.tt/1gyw6MG
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: http://ift.tt/1ft83KQ
    reporters: ['progress', 'html'],


    // 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: true,


    // start these browsers
    // available browser launchers: http://ift.tt/1ft83KU
    browsers: ['Chrome'],


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

    plugins: [
        'karma-jasmine',
        'karma-chrome-launcher',
        'karma-jasmine-html-reporter'
    ]
})
};

test-main.js

/* global System */
/* global __karma__ */

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

// Set the base url of our scripts
System.baseURL = '/base/src/';
// Here we set all the preffixes so that we'll
// be able for example to import 'test/test_name'
// instead of 'scripts/build/test_name'
System.paths = {
    'test/*': '/base/src/test/*.js',
    'build/*': '/base/src/build/*.js',
    'angular2/*': 'angular2/*',
    'rx': 'rx'
};

// paths that include spec and ends with .js
function onlySpecFiles(path) {
    return /spec\.js$/.test(path);
}

// takes paths and normalize them to module names
// by removing a base url preffix and .js suffix
function karmaFileToModule(fileName) {
    return fileName.replace(System.baseURL, '')
        .replace('.js', '');
}

Promise.all(
    Object.keys(window.__karma__.files) // Takes all files that served by karma
        .filter(onlySpecFiles)  // choose only test files
        .map(karmaFileToModule) // normalize them to module names
        .map(function (moduleName) {
            return System.import(moduleName) // import each module
                .then(function (module) {
                    if (module.hasOwnProperty('main')) {
                        module.main(); //expose the tests
                    } else {
                        throw new Error('Module ' + moduleName + ' does not implement main() method.');
                    }
                });
        })).then(function () {
        __karma__.start(); // after all tests were exposed
    }, function (error) {
        console.error(error.stack || error);
        __karma__.start();
    });

header-spec.ts

    /// <reference path="../../typings/jasmine/jasmine.d.ts" />

import {Header} from 'build/components/header/header';

export function main() {
    describe('header component', () => {

        it('should add string to header names', () => {
            var header = new Header();
            var name = 'foo';
            header.addName(name);
            expect(1).toBe(1);
        });
    });
}

header.ts

    import {Component, View, NgFor} from 'angular2/angular2';



@Component({
    selector: 'header'
})
@View({
    templateUrl: 'build/components/header/header.html',
    directives: [NgFor]
})
export class Header {
    names: Array<string>;

    constructor() {
        this.names = new Array<string>();
    }

    addName(name: string) {
        this.names.push(name);
    }
}

When I remove import Header component in my test file, tests are going ok, so it's problem with import { Component...} from 'angular2/angular2'. I don't know why karma is trying to load this as/base/src/angular2/angular2` file. I appreciate your help.

Aucun commentaire:

Enregistrer un commentaire