加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 RC.1 – 将路由器注入单元测试

发布时间:2020-12-17 06:54:44 所属栏目:安全 来源:网络整理
导读:我正在编写我的ng2测试,我遇到了一些麻烦,将Router注入我的组件进行测试.我的组件的构造函数只接受一个参数 – 私有路由器:路由器. 但是,当我运行我的测试用例时,我在尝试注入路由器时遇到错误.我究竟做错了什么?谁能提供一个有效的例子? 我正在使用angul
我正在编写我的ng2测试,我遇到了一些麻烦,将Router注入我的组件进行测试.我的组件的构造函数只接受一个参数 – 私有路由器:路由器.

但是,当我运行我的测试用例时,我在尝试注入路由器时遇到错误.我究竟做错了什么?谁能提供一个有效的例子?

我正在使用angular2-RC.1

这是我得到的错误:
没有ComponentResolver的提供者! (路由器 – > ComponentResolver)

这是我的测试:

import {describe,it,expect,beforeEach,afterEach,beforeEachProviders,inject} from "@angular/core/testing";
import {ReflectiveInjector,provide} from "@angular/core";
import {HTTP_PROVIDERS} from "@angular/http";
import {Router,ROUTER_PROVIDERS} from "@angular/router";
import {ROUTER_FAKE_PROVIDERS} from "@angular/router/testing";
import {Location} from "@angular/common";
import {SpyLocation} from "@angular/common/testing/location_mock";
import {Observable} from "rxjs/Observable";
import {MyComp} from "./MyComp";

describe("MyComp",() => {

  let injector: ReflectiveInjector,myComp: MyComp,router: Router;

  beforeEach(() => {

    injector = ReflectiveInjector.resolveAndCreate([         
      HTTP_PROVIDERS,ROUTER_FAKE_PROVIDERS,provide(Location,{useClass: SpyLocation})

    ]);

    router = injector.get(Router);
    myComp = new MyComp(router);


  });    

  afterEach(() => {
    injector = null;    
    myComp = null;
    router = null; 
  });

  it("should be defined",() => {

    expect(myComp).toBeDefined();

  });



});

解决方法

您需要为路由器创建一个jasmine间谍对象. AppComponent有一个接收路由器的构造函数.

import { AppComponent } from './app.component';
import {Router,ROUTER_PROVIDERS} from "@angular/router";

describe('app component',() => {
    let component: AppComponent;
    let router: Router;
    beforeAll(() => {
        router = jasmine.createSpyObj("Router",['navigate']);
        component = new AppComponent(router);
    });
    it("should be defined",() => {
        expect(component).toBeDefined();
    });
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读