【问题标题】:Trying to test method is called in a subscription but it's never triggered在订阅中调用了尝试测试方法,但从未触发
【发布时间】:2020-07-30 10:28:49
【问题描述】:

我有一个在 ngOnInit 中调用的方法。我想测试一下给定 ngOnInit 调用,然后触发 this.anotherService.methodToCall() 以及调用它的内容。

当我运行我的测试时,它似乎从来没有被调用过。我已经尝试了几种不同的方法来尝试这样做,但似乎没有任何效果。我是使用 Angular 和 observables 的新手,所以我可能会遗漏一些非常明显的东西。

组件的功能完全符合我的要求。因此,我基本上只是在询问有关测试此问题的最佳方法的建议。谢谢。

在component.ts中

readOnly items: Observable<TemplateItems[]> = this.itemsHandler.itemsState$;
ngOnInit(): void {
  this.checkParams();
}
private checkParams() : void {
  this.observableResult$ = combineLatest(this.items, this.activatedRoute.params]);
  this.subscriptions.add(
    this.observableResult$.subscribe(([items, params]) => {
      // During tests I never get this far
      this.anotherService.methodToCall(items, params); 
    )
  )
}

在 spec.ts - 这是我想做的事情的一个例子,但再次不确定这是否是最好的方法。

...
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      RouterTestingModule,
      ...,
    ],
    providers: [
      AnotherService,
      {
        provide: ActivatedRoute,
        useValue: {
          params: of({}),
        } 
      }
    ]
  }).compileComponents()
});
...

describe('ngOnInit', () => {
  it('should call anotherservice methodcall with filter items and params', fakeAsync (() => {
    activedRoute.params = of ({ value: "TEST_VALUE"});

    fixture.detectChanges();
    ...
    tick();

    expect(spyOfAnotherServiceMethodCall).toBeCalledWith(someItemsValue, { value: "TEST_VALUE"})
  }
}))


【问题讨论】:

  • 能否请您在tick()之前显示代码,它可以让我们更好地了解案例。还有 - 您能否在 ngOnInit 方法中添加一个 console.log 并在 activedRoute.params 调用之前添加另一个 console.log 并分享首先调用哪个。

标签: angular testing jasmine


【解决方案1】:

你需要调用tick函数(https://angular.io/api/core/testing/tick)。

【讨论】:

  • 感谢您的回复。我已经尝试过使用 tick() 函数,但它没有任何帮助。我会用打勾更新原来的帖子。
猜你喜欢
  • 1970-01-01
  • 2019-04-16
  • 2022-06-27
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
相关资源
最近更新 更多