Getting Error Cannot read property 'extras' of null when i'm running karma test

Viewed 5024

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);
3 Answers
@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

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();
});

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.

Related