Jasmine testing is not recognizing the function getCurrentNavigation(): this.router.getCurrentNavigation is not a function

Viewed 1915

I'm trying to testing a component that uses the feature getCurrentNavigation() to get data from navigation, my component is running normally without any error when i serve it with ng serve, but my testing is saying:

Component2Component > should create TypeError: this.router.getCurrentNavigation is not a function

This is what my component do to get the data:

constructor(public router: Router) {
  if (
    this.router.getCurrentNavigation() &&
    this.router.getCurrentNavigation().extras
  ) {
    console.log(this.router.getCurrentNavigation().extras);
  }

This is my test:

describe('Component2Component', () => {
  let component: Component2Component;
  let fixture: ComponentFixture<Component2Component>;
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [Component2Component],
      imports: [CommonModule, RouterTestingModule],
      providers: [{ provide: Router, useValue: routerSpy }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Component2Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Why my testing is not recognizing this function?

2 Answers

The routerSpy you provide when configuring your testing module has no function getCurrentNavigation. The only function it contains is navigate because that's what you defined when creating it through jasmine.createSpyObj.

const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

The problem could be solved by changing above line with the following one.

const routerSpy = jasmine.createSpyObj('Router', ['getCurrentNavigation', 'navigate']);

Let RouterTestingModule do its job

RouterTestingModule sets up the router to be used for testing and provides spy implementations out of the box. You're however overwriting this by providing your own routerSpy. Therefore you should get rid of your routerSpy and configure the testing module as follows.

TestBed.configureTestingModule({
  declarations: [Component2Component],
  imports: [CommonModule, RouterTestingModule]
}).compileComponents();

If you'll need access to the Router somewhere in a test function, simple retrieve it from TestBed as shown below.

it(test somethingcreate', () => {
  const router = TestBed.get(Router);
  ...
});

If you are searching this error and you think you are doing things correctly (using the RouterTestingModule) but it is still not working, double check that you imported RouterTestingModule in your imports array, not your declarations array, like I did!

Related