我想在 jasmine、karma 中测试这个功能。测试此功能的首选方法是什么。
function test(payload){
this._router.navigate([this.result.id], {relativeTo: this._activatedRoute})
}
我已经写了这个规格测试。
it('navigate to redirects', function(){
let router=TestBed.get(Router);
let spy = spyOn(router,"navigate");
const payload: any = {
event:{
body:{
result:{
collections: 0,
data: [],
errors: [],
errors_count: 0,
meta: {},
upload_id: "r1q3oFQfX"
}
}
}
};
// console.log("##################id=",payload.event.body.result.upload_id);
component.test(payload);
fixture.detectChanges();
expect(spy).toHaveBeenCalledWith([payload.event.body.result.upload_id])
});
我还创建了假课程
class RouterStub{
navigate(params){
console.log("parames",params)
}
}
并添加到 configuraTestModule
providers: [
{provide: ENGINE_CONFIG,Store,Actions,Router,useValue:routerStub,
}]
我假设您在您的组件中使用(_router:路由器)。
因此在您的测试中将添加这些行
class MockRouterService {
navigate() { }
}
const mockRouterService = new MockRouterService();
TestBed.configureTestingModule({
imports: [
...,
RouterTestingModule,
],
providers: [
{
provide: Router,
useValue: mockRouterService,
},
],
})
.compileComponents();
上面的代码将帮助您使用仅包含您要测试的功能的伪类来模拟 Router 服务。
那你就
it('should call navigate', () => {
spyOn(mockRouterService, 'navigate');
component.test(abc);
expect(mockRouterService.navigate).toHaveBeenCalled();
});
或者你可以像这样进行更具体的测试
it('should call navigate with correct params', () => {
spyOn(mockRouterService, 'navigate');
this._activatedRoute = 'your route';
component.test({id: 1});
expect(mockRouterService.navigate).toHaveBeenCalledWith([1], {relativeTo: 'your route'});
});
还有其他可能的解决方案
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router);
route = TestBed.inject(ActivatedRoute);
});
it('should navigate to path', () => {
fixture.detectChanges();
spyOn(router, 'navigate');
component.redirectToPathWithRelativeToParameter({
value: 'your path'
} as any);
fixture.detectChanges();
expect(router.navigate).toHaveBeenCalledWith(['your path'],{ relativeTo: route});
});
单元测试的组件代码涵盖:
public redirectToPathWithRelativeToParameter(option: any): void {
this.router.navigate([option.value as string], { relativeTo: this.route });
}