Fig
Fig

Reputation: 295

Angular 2 Unit test Router Navigation

Is there a way to UNIT test a router route?

I'm using Sinon to create spys and stubs.

The component

onSubmit(value: Authentication){
        this.authenticateService.getTokenFromServer(value).subscribe(v => {
            const token = this.tokenService.getToken();
            if(token){
                this.router.navigate([Config.videoPage]);

            }
        });
    }

Test

let router: any;
beforeEach(() => {
        router = createStubInstance(Router);

     it('(onSubmit() send user form to server)', () => {
            sut.onSubmit({name: 'Abc', password: '123'});
            expect(router.navigate).toHaveBeenCalledWith(['/video']);
        });

Upvotes: 2

Views: 6504

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

The main goal of unit testing is just to check if the router navigation has been called or not. Verifying actual navigation could be the part of e2e testing.

To check for the url to which the router has navigated :

expect(router.navigate).toHaveBeenCalledWith(['/video']);

If you want to check the number of times the navigation has happend within each spec:

expect(router.navigate).toHaveBeenCalledTimes(2);   

EDIT :

Creating mock router :

let router = {
            navigate: jasmine.createSpy('navigate'),    // to spy on the url that has been routed
        };

and in providers section of TestBed Configuration, add this :

providers: [{provide: Router, useValue: router}]

Upvotes: 2

Related Questions