我正在使用材料设计,需要为路线更改编写测试用例。 下面是我的HTML代码..
<button md-raised-button class="mat-primary"[routerLink]="['add']">
<i class="fa fa-plus" aria-hidden="true"></i> ADD
</button>
按钮没有任何类关联,也没有任何写入的on-click函数。 我是angular2的新手并尝试了很多测试选项,但是对于这种类型,编写jasmine单元测试用例的最佳方法是什么?
答案 0 :(得分:-1)
您需要创建模拟组件,其中包含包含路由器链接代码的组件,如下所示
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');
});
})));
});