我正在尝试在一个角组件上对Angular Karma进行一些测试,以确定路线。
该组件的结构如下
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-basic-form',
templateUrl: './basic-form.component.html',
styleUrls: ['./basic-form.component.less'],
})
export class BasicFormComponent implements OnInit {
constructor(
public activatedRoute: ActivatedRoute,
) {}
ngOnInit() {
if(this.activatedRoute.snapshot.routeConfig.path === 'basic-form/:date'){ // route with date
let date = this.route.snapshot.paramMap.get('date'); // get the date
} else {
// no worries, just use the latest date, and this component can be used on multiple routes
}
}
我的测试文件中有
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';
describe('BasicFormComponent', () => {
let component: BasicFormComponent;
let fixture: ComponentFixture<BasicFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BasicFormComponent ],
imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule, RouterTestingModule.withRoutes([])],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BasicFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
});
});
我遇到的错误是
BasicFormComponent应该创建TypeError:无法读取属性 空TypeError的“路径”:无法读取未定义的属性“快照”
为什么不导入activatedRoute模块?
我正在努力进行测试,这似乎是一门黑手艺。
任何指导将不胜感激。
答案 0 :(得分:0)
感谢@GérômeGrignon为我指出正确的方向。
下面是消除错误的答案,请在提供者中注意,其中有使用值设置。没有更多的错误。
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { BasicFormComponent } from './basic-form.component';
describe('BasicFormComponent', () => {
let component: BasicFormComponent;
let fixture: ComponentFixture<BasicFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BasicFormComponent ],
imports: [DemoMaterialModule, ReactiveFormsModule, FormsModule, HttpClientTestingModule, RouterTestingModule.withRoutes([])],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [ BasicFormComponent, {
provide: ActivatedRoute,
useValue: {snapshot: {params: {'date': ''}, routeConfig: {'path': 'basic-form-edit/:date'}}}
}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BasicFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component.activatedRoute.snapshot.routeConfig.path).toBeTruthy(); // why is this not working?
});
});