As a newcomer to unit testing with Jest in Angular, I find myself facing a challenge when it comes to testing components that utilize the this.router.navigate()
method. Previously, I used Jasmine for testing and followed these steps:
import { Router } from '@angular/router';
Then,
let router:Router;
Subsequently, within the beforeEach
block,
router = TestBed.get(Router);
Finally, in the test case itself,
it('should show news initially ', () => {
const navigateSpy = spyOn(router,'navigate');
component.showNews();
expect(navigateSpy).toHaveBeenCalledWith(['/news']);
});
This particular test was successful under Jasmine. However, I am now seeking guidance on how to achieve similar results using Jest.
In addition, there is an ngOnInit()
method implemented within my component which invokes another method called getDynamicMenus()
. The structure of the ngOnInit()
method is as follows:
ngOnInit() {
this.getDynamicMenus();
}
getDynamicMenus() {
this.menuService.getAllMenus().subscribe(menus => {
this.menus = menus._embedded.menu;
});
}
I am specifically looking for assistance in mocking this getDynamicMenus()
method. While I was able to successfully mock and invoke component.ngOnInit()
in Jasmine, I encountered difficulties attempting the same procedure in Jest. Any advice would be greatly appreciated.