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

查看:194
本文介绍了角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;
}

当我尝试测试这个组件出现问题。我添加了路由器链路的那一刻噶抱怨缺少供应商:

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

将所有的供应商后,噶是问我得到这样的:

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 - >路由器 - > RouteRegistry - >令牌RouterPrimaryComponent)。

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

原来的异常:未实现

ORIGINAL堆栈跟踪:
  错误:未实现

ORIGINAL STACKTRACE: Error: unimplemented

我在做什么错了?是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?

推荐答案

您应该有一个 beforeEachProviders 方法看起来像:

You should have a beforeEachProviders method looking like:

import {MockApplicationRef} from 'angular2/src/mock/mock_application_ref';

beforeEachProviders(() => [
  ROUTER_PROVIDERS,
  provide(APP_BASE_HREF, {useValue: '/'}),
  provide(ROUTER_PRIMARY_COMPONENT, {useValue: YourComponent}),
  provide(ApplicationRef, {useClass: MockApplicationRef}
]);

MockApplicatioRef 通过对这种测试的框架提供的。

MockApplicatioRef is provided by the framework for this kind of tests.

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

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