【问题标题】:Mocking Components with Angular 2使用 Angular 2 模拟组件
【发布时间】:2016-08-08 12:41:44
【问题描述】:

我试图模拟'Tour of Heroes' Angular 2 Tutorial 的英雄组件。但我不知道如何模拟路由器,这是实例化 HeroesComponent 所必需的。我尝试使用 Jasmine 创建一个 Spy,但这不起作用,因为它缺少属性“RootComponentType”。

我怎样才能做到这一点?

import {HeroesComponent} from "./heroes.component";
import {Router} from "@angular/router-deprecated";
import {HeroService} from "./hero.service";


describe('HeroesComponent', () => {
    let heroes:HeroesComponent;
    let router:Router;
    let service:HeroService;
    beforeEach(() => {
        router = jasmine.createSpyObj('Router', ['navigate']);
        service = new HeroService(/* I will care about this later */);
        heroes = new HeroesComponent(router, service);
    });
    it('should be defined', () => {
        expect(heroes).toBeDefined();
    });
});

它正在工作:

describe('HeroesComponent', () => {
    let router:any;
    let heroesComponent:HeroesComponent;
    let service:HeroService;

    beforeEach(() => {
        router = new class {
            navigate = jasmine.createSpy("navigate");
        };
        heroesComponent = new HeroesComponent(router, service);
    });
    it('should be defined', () => {
        expect(heroesComponent).toBeDefined();
    });
});

【问题讨论】:

    标签: angularjs unit-testing testing angular


    【解决方案1】:

    您可以直接在导航方法上创建间谍。

    1. 为 DI 使用 addProviders:

      beforeEach(() => addProviders([
      { 
          provide: Router, 
          useClass: class { navigate = jasmine.createSpy("navigate"); }
      }]));
      
    2. 对于组件的直接初始化:

      let router;
      let heroesComponent;
      
      beforeEach(() => {
          router = new class { navigate = jasmine.createSpy("navigate"); };
          heroesComponent = new HeroesComponent(router);
      });
      

    【讨论】:

    • 谢谢,但是如何为 HeroesComponent 构造函数提供提供者?
    • @JoCa 相应地调整了答案。
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2017-09-14
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2021-08-18
    • 2016-04-29
    相关资源
    最近更新 更多