我最近在学习角度测试。所以我创建了一个由路由器根据数字 id 使用的组件。
在我的组件代码中,我使用以下方法获取 id 值:
id = 0;
getId : number () {
this.id = Number(this.route.snapshot.paramMap.get('id'));
}
我的测试spec.ts文件如下:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { RoutingByIdComponent } from './routing-by-id.component';
describe('RoutingByIdComponent', () => {
let component: RoutingByIdComponent;
let fixture: ComponentFixture<RoutingByIdComponent>;
const activatedRouteMock = {
paramMap: of({ get: (param: string) => '1' }),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [RoutingByIdComponent],
providers: [{ provide: ActivatedRoute, useValue: activatedRouteMock }],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RoutingByIdComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在“ng test”命令之后,我在 Karma 上收到错误消息:
TypeError: Cannot read properties of undefined (reading 'paramMap')
如果我将 id 值声明为
id = 0
而没有从 ActivatedRoute 测试中获取它,效果就很好!
所以问题是通过使用
getId()
函数和 ActivatedRoute 出现的。
这可能是什么原因造成的?
你可以用 jasmine 来模拟activatedRoute。我在我的组件中设置了这个
private activatedRoute = inject(ActivatedRoute);
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.callMe(id);
}
callMe(id: any) {
console.log('Called with id: ', id);
}
这是我的规格:
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AppComponent } from "./app.component";
import { ActivatedRoute, convertToParamMap } from '@angular/router';
fdescribe("AppComponent", () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let activatedRoute: jasmine.SpyObj<ActivatedRoute>;
const snapshot = {
paramMap: convertToParamMap({ id: 1 })
};
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
{
provide: ActivatedRoute,
useValue: activatedRoute
}
],
imports: []
}).compileComponents();
});
activatedRoute = jasmine.createSpyObj('ActivatedRoute', [], { snapshot });
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
activatedRoute = TestBed.inject(ActivatedRoute) as jasmine.SpyObj<ActivatedRoute>;
fixture.detectChanges();
});
it('should call callMe with the correct id', () => {
const id = 1;
spyOn(component, 'callMe');
component.ngOnInit();
expect(component.callMe).toHaveBeenCalledWith(id);
});
});