我的构造函数中有以下代码
constructor(
private ngxSpinner: NgxSpinnerService,
private userSecurityService: UserSecurityService,
private userInformationService: UserInformationService,
private navigateService: NavigateService,
private titleService: Title,
private router: Router
) {
this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
this.currentPath = event.url;
if(this.currentPath.indexOf('/custom-fields?view=edit') > -1) {
this.isCustomfieldsPage = true;
} else {
this.isCustomfieldsPage = false;
}
});
}下面是我的测试用例
it('check if isCustomfieldsPage is true', () => {
spectator.component.isCustomfieldsPage = true;
spectator.component.currentPath = 'https://csc.com/admin/custom-fields?view=edit';
expect(spectator.component.isCustomfieldsPage).toBe(true);
});
it('check if isCustomfieldsPage is false', () => {
spectator.component.isCustomfieldsPage = false;
spectator.component.currentPath = 'https://csc.com/admin/manage-fields';
expect(spectator.component.isCustomfieldsPage).toBe(false);
});上面的测试用例没有覆盖构造器内部的代码吗?我如何修改我的代码才能按预期工作。请提个建议。谢谢。
发布于 2021-11-30 09:59:38
这在不查找现有测试的情况下有点通用,但是你可以这样做:
const router: Router
const myComponent: Mycomponent
const routerEventsObserver;
beforeEach(() => {
// set up test bed
})
beforeEach(() => {
router = TestBed.inject(Router);
router.events = new Observable((observer) => {
routerEventsObserver = observer
});
myComponent = TestBed.createComponent(MyComponent);
})顺序在这里很重要。您将获得路由器的一个实例,并将可观察到的内部事件替换为您手动创建的内部事件,并在创建组件之前执行此操作。创建组件时,将监听修改后的router.events可观察对象。
现在编写你的测试:
it('should do something', () => {
// create mock result object representing NavigationEnd
routerEventsObserver.next(My mock result object);
// assertions
})编辑为:即使您将代码移动到ngOnInit()并手动调用它,正如注释中所建议的那样,我仍然会使用类似的方法:模拟服务中的可观察对象,获取对内部观察者的引用。并控制订阅函数运行的时间
https://stackoverflow.com/questions/70167177
复制相似问题