我是使用 Angular 中的 Jest 进行单元测试的初学者。在我的组件中,我有 this.router.navigate()
方法。早些时候我用 Jasmine 来测试它。为此,我做了以下事情:
import { Router } from '@angular/router';
然后,
let router:Router;
然后,在beforeEach
中,
router = TestBed.get(Router);
然后,在测试用例中,
it('should show news intially ', () => {
const navigateSpy = spyOn(router,'navigate');
component.showNews();
expect(navigateSpy).toHaveBeenCalledWith(['/news']);
});
这个测试通过了。但是我如何使用 Jest 做同样的事情呢?请帮忙。
我有一个 ngOnInit()
方法调用另一个方法 getDynamicMenus()
。下面是 ngOnInit()
方法:
ngOnInit() {
this.getDynamicMenus();
}
getDynamicMenus() {
this.menuService.getAllMenus().subscribe(menus => {
this.menus = menus._embedded.menu;
});
}
请告诉我如何模拟此方法。在 jasmine 中,我模拟了 getDynamicMenus()
并调用了 component.ngOnInit()
。但这在 Jest 中不起作用。请帮忙。
最佳答案
Jasmine spyOn()
函数的等价物是 jest.spyOn(object, methodName) .
it('should show news intially ', () => {
const navigateSpy = jest.spyOn(router,'navigate');
component.showNews();
expect(navigateSpy).toHaveBeenCalledWith(['/news']);
});
关于angular - 如何在 Jest 中模拟 router.navigate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66872744/