0

I am using material design and need to write test case for route change.. below is my html code..

 <button md-raised-button class="mat-primary"[routerLink]="['add']">
 <i class="fa fa-plus" aria-hidden="true"></i> ADD
 </button>

There is no any class associate to button and also don't have any on-click function written. I am new in angular2 and tried many options to test, but for this kind what is best approach to write jasmine unit test case?

crashmstr
  • 28,043
  • 9
  • 61
  • 79
sag Surya
  • 199
  • 1
  • 3
  • 16
  • We do not edit titles with "Duplicate". Instead use close votes as such, and if you don't have the votes, post a link in the comments, like this: [Angular 2 unit testing components with routerLink](https://stackoverflow.com/questions/39577920/angular-2-unit-testing-components-with-routerlink). Rolling back the question. – crashmstr Aug 28 '17 at 17:20

1 Answers1

-1

You need to create mock component which includes component which contains your router link code like as below

Angular 2 unit testing components with routerLink

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

@Component({
  template: `
    <a routerLink="/settings/{{collName}}/edit/{{item._id}}">link</a>
    <router-outlet></router-outlet>
  `
})
class TestComponent {
  collName = 'testing';
  item = {
    _id: 1
  };
}

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

describe('component: TestComponent', function () {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([
         { path: 'settings/:collection/edit/:item', component: DummyComponent }
        ])
      ],
      declarations: [ TestComponent, DummyComponent ]
    });
  });

  it('should go to url',
    async(inject([Router, Location], (router: Router, location: Location) => {

    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    fixture.debugElement.query(By.css('a')).nativeElement.click();
    fixture.whenStable().then(() => {
      expect(location.path()).toEqual('/settings/testing/edit/1');
      console.log('after expect');
    });
  })));
});
Rohan Fating
  • 2,135
  • 15
  • 24