首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular -是否可以为构造函数中的代码编写测试用例?

Angular -是否可以为构造函数中的代码编写测试用例?
EN

Stack Overflow用户
提问于 2021-11-30 09:41:40
回答 1查看 46关注 0票数 0

我的构造函数中有以下代码

代码语言:javascript
复制
  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;
      }
    });
  }

下面是我的测试用例

代码语言:javascript
复制
  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);
  });

上面的测试用例没有覆盖构造器内部的代码吗?我如何修改我的代码才能按预期工作。请提个建议。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-11-30 09:59:38

这在不查找现有测试的情况下有点通用,但是你可以这样做:

代码语言:javascript
复制
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可观察对象。

现在编写你的测试:

代码语言:javascript
复制
it('should do something', () => {
  // create mock result object representing NavigationEnd
  routerEventsObserver.next(My mock result object);
  // assertions 
})

编辑为:即使您将代码移动到ngOnInit()并手动调用它,正如注释中所建议的那样,我仍然会使用类似的方法:模拟服务中的可观察对象,获取对内部观察者的引用。并控制订阅函数运行的时间

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70167177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档