'Getting Error Cannot read property 'extras' of null when i'm running karma test
I made a component and I'm using the following code to get some data from the route. When I'm trying ng test I'm getting an error:
TypeError: Cannot read property 'extras' of null
What I should import on the spec file of this component to read the "state"? On my spec file I added the import { RouterTestingModule } from '@angular/router/testing' but still doesn't work;
const navigation = this.router.getCurrentNavigation();
const state = navigation.extras.state;
console.log(state);
Solution 1:[1]
@Component({
selector: 'app-root',
template: `<pre>{{ state$ | async | json }}</pre>`,
})
export class AppComponent implements OnInit {
private state$: Observable<object>;
constructor(public router: Router) { }
ngOnInit() {
this.state$ = this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
)
}
}
For more info: Passing Data between Routes in Angular
Solution 2:[2]
In my case, I fixed all these errors by adding
afterEach(() => {
TestBed.resetTestingModule();
});
In all of my *.spec.ts files.
My files looks like this:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
afterEach(() => {
TestBed.resetTestingModule();
});
Solution 3:[3]
You need to check with if statement.
data: '';
constructor(public router: Router) {
let data = this.router.getCurrentNavigation().extras.state;
if(data)
this.data = data;
}
Important* The above code needs to be in your constructor() as this will always make sure you have access to data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ediz Nezir |
| Solution 2 | Pal |
| Solution 3 | Olu Ayeni |
