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

如何将angular2服务注入单元测试? (RC3)

发布时间:2020-12-17 06:48:37 所属栏目:安全 来源:网络整理
导读:我正在使用RC3.我正在实现新的Angular2路由器,如下所述: https://angular.io/docs/ts/latest/guide/router.html 一切正常但我在单元测试中遇到问题.具体来说,我不能将Angular2服务注入我的单元测试中. 我的相关组件代码是: import {Component} from '@angu
我正在使用RC3.我正在实现新的Angular2路由器,如下所述: https://angular.io/docs/ts/latest/guide/router.html

一切正常但我在单元测试中遇到问题.具体来说,我不能将Angular2服务注入我的单元测试中.

我的相关组件代码是:

import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  templateUrl: ...
  styleUrls: ...
})

export class Route1DetailComponent {

  constructor(private route:ActivatedRoute) {
    console.log(route);
  }
}

我的单元测试看起来像:

import {
  expect,it,iit,xit,describe,ddescribe,xdescribe,beforeEach,beforeEachProviders,withProviders,async,inject
} from '@angular/core/testing';

import {ActivatedRoute} from '@angular/router';
import {Route1DetailComponent} from './route1-detail.component';
import {TestComponentBuilder} from '@angular/compiler/testing';

describe('route1-detail.component.ts',() => {

  beforeEachProviders(() => [
    {provide: ActivatedRoute,useClass: ActivatedRoute}
  ]);

  it('should instantiate component',async(inject([TestComponentBuilder,ActivatedRoute],(tcb:TestComponentBuilder,ar: ActivatedRoute) => {
      tcb.createAsync(Route1DetailComponent).then((fixture) => {
        expect(fixture.componentInstance instanceof Route1DetailComponent).toBe(true,'should create Route1DetailComponent');
        console.log(ar);
    });
  })));

});

‘should instantiate component’单元测试失败.错误是:

Cannot resolve all parameters for ‘ActivatedRoute'(?,?,?).
Make sure that all the parameters are decorated with Inject or have
valid type annotations and that ‘ActivatedRoute’ is decorated with
Injectable.

我该如何工作?

当我不注射ActivatedRoute时一切正常.

谢谢.

解决方法

在单元测试时,有时某个服务会因为没有在正常环境中使用而导致问题.您可以测试是否已调用它,而无需通过整个服务运行单元测试.通过创建一个模拟类来做到这一点.

describe('route1-detail.component.ts',() => {

class MockActivatedRoute {}

beforeEachProviders(() => [
    {provide: ActivatedRoute,useClass: MockActivatedRoute}
  ]);

it('should instantiate component',ar: MockActivatedRoute) => {
  tcb.createAsync(Route1DetailComponent).then((fixture) => {
    expect(fixture.componentInstance instanceof Route1DetailComponent).toBe(true,'should create Route1DetailComponent');
    console.log(ar);
  });
})));

注意这一部分:inject([TestComponentBuilder,(tcb:TestComponentBuilder,ar:MockActivatedRoute.当代码正在寻找ActivatedRoute时,你传递模拟服务.当然,如果您专门尝试对ActivatedRoute本身进行单元测试,那么创建模拟服务就会失败.如果尝试从该服务调用方法,则可能必须向mock类添加方法或变量.

(编辑:李大同)

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

    推荐文章
      热点阅读