我正试图模仿'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();
});
});
答案 0 :(得分:1)
您可以直接在导航方法上创建间谍。
在DI中使用addProviders:
beforeEach(() => addProviders([
{
provide: Router,
useClass: class { navigate = jasmine.createSpy("navigate"); }
}]));
直接初始化组件:
let router;
let heroesComponent;
beforeEach(() => {
router = new class { navigate = jasmine.createSpy("navigate"); };
heroesComponent = new HeroesComponent(router);
});