jeudi 30 juillet 2020

Angular 8 | Jasmine | Trying to test method is called in a subscription but it's never triggered

I have a method that is called in an ngOnInit. I want to test that given the ngOnit call then this.anotherService.methodToCall() is triggered and what it is being called with.

It just never seems to be called when I run my tests. I've tried several different ways to try and do this but nothing seems to work. I'm pretty new working with Angular and observables so I might be missing something very obvious.

The functionality of the component does exactly what I want it to do. So i'm basically just asking on advice on what the best method to test this would be. Thanks.

In 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]) => {
      this.anotherService.methodToCall(items, params); 
    )
  )
}

in spec.ts - This is an example of the sorta thing I would like to do but once again not sure if this is the best way to approach.

...
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', () => {
    activedRoute.params = of ({ value: "TEST_VALUE"});

    fixture.detectChanges();
    ...

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


Aucun commentaire:

Enregistrer un commentaire