使用Karma运行Angular 2测试,与templateUrl有关

时间:2016-03-14 16:12:09

标签: angular karma-runner

在我的组件中使用templateUrl时,我在使用Karma运行Angular 2测试时遇到了一些麻烦。

这是我的业力配置文件:

'use strict';

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    autoWatchBatchDelay: 3000,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'node_modules/zone.js/dist/zone-microtask.js',
      'node_modules/zone.js/dist/long-stack-trace-zone.js',
      'node_modules/zone.js/dist/jasmine-patch.js',
      'node_modules/es6-module-loader/dist/es6-module-loader.js',
      'node_modules/traceur/bin/traceur-runtime.js', // Required by PhantomJS2, otherwise it shouts ReferenceError: Can't find variable: require
      'node_modules/traceur/bin/traceur.js',
      'node_modules/systemjs/dist/system.src.js',
      'node_modules/reflect-metadata/Reflect.js',
      // beta.7 IE 11 polyfills from https://github.com/angular/angular/issues/7144
      'node_modules/angular2/es6/dev/src/testing/shims_for_IE.js',

      { pattern: 'node_modules/angular2/**/*.js', included: false, watched: false },
      { pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
      { pattern: 'dist/dev/**/*.js', included: false, watched: true },
      { pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: false, watched: false }, // PhantomJS2 (and possibly others) might require it
      'test-main.js'
    ],

    // list of files to exclude
    exclude: [
      'node_modules/angular2/**/*spec.js'
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'dist/**/!(*spec).js': ['coverage']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha', 'coverage'],


    coverageReporter: {
      dir: 'coverage/',
      reporters: [
        { type: 'text-summary' },
        { type: 'json', subdir: '.', file: 'coverage-final.json' },
        { type: '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: [
      'PhantomJS'
    ],



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

};

以下是一个示例模块:

import {Component} from 'angular2/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/common';

import {NameList} from '../../shared/services/name_list';

@Component({
  selector: 'about',
  moduleId: module.id, // using relative paths, see http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/
  templateUrl: './about.html',
  styleUrls: ['./about.css'],
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES]
})
export class AboutCmp {
  newName;
  constructor(list = new NameList()) {
    this.list = list;
  }
 /*
 * @param newname  any text as input.
 * @returns return false to prevent default form submit behavior to refresh the page.
 */
  addName() {
    this.list.add(this.newName);
    this.newName = '';
    return false;
  }
}

和我的测试规范文件:

import {
  TestComponentBuilder,
  describe,
  expect,
  injectAsync,
  it
} from 'angular2/testing';
import {Component} from 'angular2/core';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {AboutCmp} from './about';
import {NameList} from '../../shared/services/name_list';


export function main() {
  describe('About component', () => {
    it('should work',
      injectAsync([TestComponentBuilder], (tcb) => {
        return tcb.createAsync(TestComponent)
          .then(rootTC => {
            rootTC.detectChanges();

            let aboutInstance = rootTC.debugElement.children[0].componentInstance;
            let aboutDOMEl = rootTC.debugElement.children[0].nativeElement;
            let nameListLen = function () {
              return aboutInstance.list.names.length;
            };

            expect(aboutInstance.list).toEqual(jasmine.any(NameList));
            expect(nameListLen()).toEqual(4);
            expect(DOM.querySelectorAll(aboutDOMEl, 'li').length).toEqual(nameListLen());

            aboutInstance.newName = 'Minko';
            aboutInstance.addName();
            rootTC.detectChanges();

            expect(nameListLen()).toEqual(5);
            expect(DOM.querySelectorAll(aboutDOMEl, 'li').length).toEqual(nameListLen());

            expect(DOM.querySelectorAll(aboutDOMEl, 'li')[4].textContent).toEqual('Minko');
          });
      }));
  });
}

@Component({
  providers: [NameList],
  selector: 'test-cmp',
  template: '<about></about>',
  directives: [AboutCmp]
})
class TestComponent {}

我遇到的问题是在运行构建系统(使用gulp)之后,然后将所有已编译的文件和css移动到项目根目录下的另一个文件夹中:/ dist / dev / all-my-files -are-移动-这里。

移动文件后的示例结构:

dist/dev/about/components/about.js
dist/dev/about/components/about.html
dist/dev/about/components/about.css

这是我得到的警告和错误:

14 03 2016 16:55:26.687:WARN [web-server]: 404: /base/dist/dev/about/components/about.html

SUMMARY:
✔ 1 test completed
✖ 3 tests failed

FAILED TESTS:
  About component
    ✖ should work
      PhantomJS 2.1.1 (Mac OS X 0.0.0)
    Failed: Failed to load /Users/ogran83/Developer/Projects/angular2-seed/dist/dev/about/components/about.html
    run@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:1217:29
    zoneBoundFn@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:1194:29
    lib$es6$promise$$internal$$tryCatch@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:442:25
    lib$es6$promise$$internal$$invokeCallback@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:454:53
    lib$es6$promise$$internal$$publish@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:425:53
    lib$es6$promise$$internal$$publishRejection@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:375:42
    /Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:97:12
    run@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:1217:29
    zoneBoundFn@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:1194:29
    lib$es6$promise$asap$$flush@/Users/ogran83/Developer/Projects/angular2-seed/node_modules/zone.js/dist/zone-microtask.js:236:18

文件/Users/ogran83/Developer/Projects/angular2-seed/dist/dev/about/components/about.html显然存在,但在PhantomJS中由karma运行时似乎不起作用。在浏览器中测试时,应用程序本身运行正常。

1 个答案:

答案 0 :(得分:2)

这是一个已知问题

当组件具有templateUrl https://github.com/angular/angular/issues/5662

时,

TestComponentBuilder / inject不起作用