angular - 使用 Karma 运行 Angular 2 测试,templateUrl 出现问题

标签 angular karma-runner

在组件中使用 templateUrl 时,我在使用 Karma 运行 Angular 2 测试时遇到一些问题。

这是我的 karma 配置文件:

'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 -已移至此处。

移动文件后的示例结构:

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 运行时似乎不起作用。在浏览器中测试时,应用程序本身运行良好。

最佳答案

这是一个已知问题

当组件具有 templateUrl https://github.com/angular/angular/issues/5662 时,TestComponentBuilder/inject 不起作用

关于angular - 使用 Karma 运行 Angular 2 测试,templateUrl 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992569/

相关文章:

javascript - 将组件 Assets 放在自己的目录中

javascript - angular2-tree-component 默认不展开

angular - 配置 Angular 服务以在 AngularJS 模块单元测试中使用

angularjs - 使用模拟 httpBackend 进行 Angular E2E 测试?

angular - 使用 Angular 在单元测试覆盖率中包含组件模板

javascript - 从 typescript 将值作为空字符串传递给 WEb API

node.js - 如何在 Angular2 中使用 'crypto' 模块?

angular - 使用 AOT 时,对传递给 forRoot 的对象所做的更改在注入(inject)时会被丢弃

javascript - 为什么这个针对 angular-google-maps 提供者的测试失败了?

javascript - 由于套接字 io 不存在导致测试失败