2

I am attempting to test my Router in Angular 2.2.1 to ensure the proper routes are set up and going to the expected location. I've done Google research and have read and re-read the app.component.router.spec.ts file from the example at https://angular.io/docs/ts/latest/guide/testing.html and am still falling short.

I found a really good answer here that was easy to understand and appeared obvious: Angular 2 Final Release Router Unit Test

So using that, I created this as a test for my own Router:

import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { fakeAsync, async, inject, TestBed, getTestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

@Component({
    template: '<router-outlet></router-outlet>'
})
class RoutingComponent { }

@Component({
    template: ''
})
class DummyComponent { }

describe('component: RoutingComponent', () => {
    let location, router;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule.withRoutes([
                { path: 'home', component: DummyComponent },
                { path: 'not-exists', component: DummyComponent }
            ])],
            declarations: [RoutingComponent, DummyComponent]
        });
    });

    beforeEach(inject([Router, Location], (_router: Router, _location: Location) => {
        location = _location;
        router = _router;
    }));

    it('should fail, but does not', async(() => {
        let fixture = TestBed.createComponent(RoutingComponent);
        fixture.detectChanges();
        router.navigate(['not-exists']).then(() => {
            expect(location.path()).toBe('/not-exists');
            console.log('after expect');
        });
    }));
});

The problem I'm having is that I don't understand how this is testing my real router. As you can see I created a path in here called 'not-exists' that goes to a dummy component and, as the name indicates, this route does not exist in my real router. This makes me believe that it really isn't testing anything except for the paths that I put here.

So my questions are:

  1. How can I test my real router so that if routes change this test breaks?
  2. How can I test my router where it goes to one path but redirects to another? (For example I have a path '/' that redirects to '/home')
  3. Is it possible to test my real router where a particular path goes to a particular component?

Thanks!

Community
  • 1
  • 1
user27519
  • 21
  • 3
  • 2
    I would test the routing end-to-end, rather than as a unit test; it requires multiple components working together. – jonrsharpe Nov 29 '16 at 16:02

0 Answers0