gpt4 book ai didi

angularjs - 使用 Angular 2 模拟组件

转载 作者:行者123 更新时间:2023-11-28 20:39:38 25 4
gpt4 key购买 nike

我正在尝试模拟 'Tour of Heroes' Angular 2 Tutorial 的 Heroes-Component| .但是我不知道如何模拟实例化 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();
});
});

最佳答案

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

  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);
    });

关于angularjs - 使用 Angular 2 模拟组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com