Reputation: 31
I want test this function in jasmine, karma. what is the prefer way to test this function.
function test(payload){
this._router.navigate([this.result.id], {relativeTo: this._activatedRoute})
}
I have wrote the spec test this.
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])
});
as well i created the fake class
class RouterStub{
navigate(params){
console.log("parames",params)
}
}
and add to the configuraTestModule too
providers: [
{provide: ENGINE_CONFIG,Store,Actions,Router,useValue:routerStub,
}]
Upvotes: 3
Views: 5561
Reputation: 1820
there is other possible solution
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});
});
component code for unit tests covering:
public redirectToPathWithRelativeToParameter(option: any): void {
this.router.navigate([option.value as string], { relativeTo: this.route });
}
Upvotes: 0
Reputation: 527
Let I assume that in your component you use (_router: Router).
So in your test would be adding these lines
class MockRouterService {
navigate() { }
}
const mockRouterService = new MockRouterService();
TestBed.configureTestingModule({
imports: [
...,
RouterTestingModule,
],
providers: [
{
provide: Router,
useValue: mockRouterService,
},
],
})
.compileComponents();
The code above will help you to mock the Router service with the fake class that only contain the function that you want to test.
then you just
it('should call navigate', () => {
spyOn(mockRouterService, 'navigate');
component.test(abc);
expect(mockRouterService.navigate).toHaveBeenCalled();
});
or you can test even more specific like this
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'});
});
Upvotes: 1