Here is my method in ts file: this method called upon click on any of the td
from the table. event passing the row data. null is accpeted.
initiateDetailsView(detailsData): void {
this.personalDataService.userDetails$.next(detailsData);
this.router.navigate(['./personnel-details'], {
relativeTo: this.activatedRoute,
});
}
I am trying to do the testing the same method like this:
it('should call initiateDetailsView list click and need to redirect to profile page', fakeAsync(async () => {
const initiateDetailsView = spyOn(
component,
'initiateDetailsView'
).and.callThrough();
component.tableSchema = testHFSTaleSchema;
component.setPersonnelList();
tick(1000);
const tds = fixture.debugElement.query(By.css('td'));
tds.nativeElement.click(null);
expect(initiateDetailsView).toHaveBeenCalledWith(null);
}));
but getting an error as:
ERROR: 'ERROR', TypeError: Cannot read properties of undefined (reading '_lastPathIndex')
the above error thrown from router
. But do not know have to address this issue in test. any one please help me here? how can test the method which has the router navigate?
CodePudding user response:
It looks like you are trying to use the router in your test, but it is not properly initialized. The Router class has a initialNavigation property that needs to be set to false when testing, otherwise it will throw an error when you try to navigate to a different route.
To fix this issue, you can import the RouterTestingModule in your test and include it in the imports array of the TestBed configuration. This will provide a mocked Router instance for your test that will not throw an error when you try to navigate to a different route.
Here is an example of how you can update your test to fix the error:
import { fakeAsync, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [ RouterTestingModule ],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should call initiateDetailsView list click and need to redirect to profile page', fakeAsync(async () => {
const initiateDetailsView = spyOn(
component,
'initiateDetailsView'
).and.callThrough();
component.tableSchema = testHFSTaleSchema;
component.setPersonnelList();
tick(1000);
const tds = fixture.debugElement.query(By.css('td'));
tds.nativeElement.click(null);
expect(initiateDetailsView).toHaveBeenCalledWith(null);
}));
});
This should fix the error and allow your test to properly navigate to the personnel-details route.