Angular 2:使用路由器测试组件 [英] Angular 2: Testing components with router

查看:26
本文介绍了Angular 2:使用路由器测试组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写使用 routeLink 的最简单的组件:

I am writing the simplest component that is using a routeLink:

@Component({
    selector: 'memorySnippet',
    templateUrl: '<div class="memory-snippet-wrapper" *ngIf="memory" 
                  [routerLink]="['MainPanel', 'MemoryPanel', {'id' : this.memory.id}]">',
    directives: [CORE_DIRECTIVES, ROUTER_DIRECTIVES]
})
export class MemorySnippetComponent {
    @Input() memory: Memory;
}

当我尝试测试此组件时出现问题.我添加路由器链接的那一刻 Karma 抱怨缺少提供商:

The problem occurs when I try testing this component. The moment I add the router link Karma is complaining about missing providers:

在添加了 Karma 要求的所有提供者后,我得到了这个:

After adding all the providers Karma is asking I get this:

beforeEachProviders(() => [
    MemorySnippetComponent,
    MEMORY_SERVICE_PROVIDERS,
    ROUTER_PROVIDERS,
    ApplicationRef
]);

但是当我运行测试时出现此错误:

But when I run the test I get this error:

例外:例外:令牌 RouterPrimaryComponent 实例化过程中出错!(RouterLink -> Router -> RouteRegistry -> Token RouterPrimaryComponent).

EXCEPTION: EXCEPTION: Error during instantiation of Token RouterPrimaryComponent! (RouterLink -> Router -> RouteRegistry -> Token RouterPrimaryComponent).

原始例外:未实施

原始堆栈跟踪:错误:未实现

ORIGINAL STACKTRACE: Error: unimplemented

我做错了什么???Angular 2 (2.0.0-beta.1) 还没有准备好测试带有路由器指令的组件吗?

What am I doing wrong??? Is Angular 2 (2.0.0-beta.1) just not ready for testing components with router directives?

推荐答案

对于带有新路由器的 RC4 现在使用 ...

For RC4 with new router now use ...

beforeEach(() => addProviders([
  APP_ROUTER_PROVIDERS, // must be first
  {provide: APP_BASE_HREF, useValue: '/'}, // must be second
  {provide: ActivatedRoute, useClass: Mock},
  {provide: Router, useClass: Mock}
]));

使用这种方法的 github 项目是......

A github project using this approach is ...

https://github.com/danday74/angular2-coverage

这篇关于Angular 2:使用路由器测试组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆