JoCa JoCa - 4 months ago 42
AngularJS Question

Mocking Components with Angular 2

I am trying to mock the Heroes-Component of the 'Tour of Heroes' Angular 2 Tutorial. But I don't know how to mock the router, which is needed for instantiating the HeroesComponent. I tried to create a Spy with Jasmine, but that doesn't work, because it is missing the property 'RootComponentType'.

How can I make this work?

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


It is working now:

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

Answer

You could create a spy directly on a navigate method.

  1. Using addProviders for DI:

    beforeEach(() => addProviders([
    { 
        provide: Router, 
        useClass: class { navigate = jasmine.createSpy("navigate"); }
    }]));
    
  2. For a directly initialization of a component:

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