在为Angular2运行测试时获取模板解析错误

时间:2017-02-09 18:59:05

标签: angular gulp webpack-2

民间,

我在运行Angular2的单元测试时遇到问题(我为此使用了gulp任务),但是当我尝试时出现以下错误:

Failed: Template parse errors:
        Can't bind to 'routerLink' since it isn't a known property of 'a'. ("     <ul class="nav navbar-nav navbar-right">
                <li routerLinkActive="active">
                  <a [ERROR ->][routerLink]="['signup']">Sign Up</a>
                  <a [routerLink]="['login']">Login</a>
                </li>"): HeaderComponent@15:13

当我从HTML模板中删除对routerLink的引用时,一切正常。以下是我的webpack.test.js文件的定义:

var webpack = require('webpack');
var helpers = require('./helpers');

module.exports = {
  devtool: 'inline-source-map',

  resolve: {
    extensions: ['.ts', '.js']
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders:
          [
            'awesome-typescript-loader',
            'angular2-template-loader'
          ]
      },
      {
        test: /\.html$/,
        loader: 'html-loader'

      },
      {
        test: /\.scss$/,
        loaders: [ 'raw-loader', 'sass-loader' ]
      },
    ]
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('./client/src'), // location of your src
      {} // a map of your routes
    )
  ]
};

这是我试图运行的测试:

describe("HeaderComponent", () => {
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HeaderComponent],
    });
    fixture = TestBed.createComponent(HeaderComponent);
    fixture.detectChanges();
  }));

  it('should display a form to register', () => {
    let navbar = fixture.debugElement.query(By.css('navbar'));
    console.log(navbar);
    expect(navbar).toBeDefined();
  });
});

任何人都有任何想法,我错过了什么?我的正常webpack.dev.js无任何问题。这是我的测试设置特有的东西。我无法弄清楚我做错了什么。我也尝试删除angular2-template-loader,但是因为无法找到模板而得到了一个不同的错误 - 这至少是有意义的。

2 个答案:

答案 0 :(得分:0)

您是否在测试中设置了路由设置?没有这些,解析器将无法理解该指令。

答案 1 :(得分:0)

您未在测试设置中包含RouterModule和必要的提供程序:

import { RouterModule } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

TestBed.configureTestingModule({
  imports: [
    RouterModule.forRoot([], {useHash: false})
  ],
  declarations: [ ComponentUnderTest ],
  providers: [
    { provide: APP_BASE_HREF, useValue: '/' }
  ]
})