How to mock the router.navigate method in jest

I am a beginner in unit testing using Jest in Angular. In my component, I have the this.router.navigate() method. Earlier I was using Jasmine to test it. For that I had done the following:

import { Router } from '@angular/router';

Then,

let router:Router;

Then, in the beforeEach,

router = TestBed.get(Router);

Then, in the testcase,

it('should show news intially ', () => {
   const navigateSpy = spyOn(router,'navigate');
   component.showNews();
   expect(navigateSpy).toHaveBeenCalledWith(['/news']);
 });

This test was passed. But how do I do the same using Jest? Please Help.

I have an ngOnInit() method which calls another method getDynamicMenus(). Below is the ngOnInit() method:

 ngOnInit() {
    this.getDynamicMenus();
  }


  getDynamicMenus() {
    this.menuService.getAllMenus().subscribe(menus => {
      this.menus = menus._embedded.menu;
    });
  }

Please let me know how to mock this method. In jasmine, I mocked the getDynamicMenus() and called component.ngOnInit(). But this doesn't work in Jest. Please help.

Upvotes: 7

Views: 22353

Answers (1)

Lin Du
Lin Du

Reputation: 102207

The equivalent of the jasmine spyOn() function is jest.spyOn(object, methodName).

it('should show news intially ', () => {
   const navigateSpy = jest.spyOn(router,'navigate');
   component.showNews();
   expect(navigateSpy).toHaveBeenCalledWith(['/news']);
});

Upvotes: 9

Related Questions