使用Karma进行Angular 2单元测试

时间:2015-10-29 10:46:05

标签: unit-testing typescript karma-runner angular

我正在学习Angular2,现在正尝试使用Karma进行一些单元测试。

我根据这篇文章https://dimakuzmich.wordpress.com/2015/08/21/test-angular2-now-or-how-to-set-up-angular2-unit-tests/配置了我的项目,但是当我运行单元测试时,我得到以下错误:

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

我有gulp任务,可以将我的ts文件编译成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: https://npmjs.org/browse/keyword/karma-adapter
    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: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    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: https://npmjs.org/browse/keyword/karma-launcher
    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'
    ]
})
};

测试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();
    });

头-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);
    }
}

当我删除测试文件中的import Header组件时,测试运行正常,因此'angular2 / angular2'中的`import {Component ...}会出现问题。

我不知道为什么业力会尝试将其加载为/base/src/angular2/angular2文件。感谢您的帮助。

0 个答案:

没有答案