Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Jasmine this service method is a not a function

I am trying to get a service method to pass inside a unit test, however it keeps failing:

"TypeError: this.eventsService.getEvent is not a function"

My code inside my component:

constructor(
 private eventsService: EventsService
)

this.subscriptions.add(
  this.eventsService.getEvent().subscribe(events => {
    this.events = events;
    this.soSomeMethod();
  })
);
// Also have a V2 method, unsure if it matters but adding it for clarity
this.subscriptions.add(
  this.eventsService.getEventV2().subscribe(eventsV2 => {
    this.eventsV2 = eventsV2;
    this.soSomeMethod();
  })
);

This is the service in question:

  public getEvent(): Observable<event[]> {
    return combineLatest(this.store.select(getEventStore), this.store.select(getEvents)).pipe(
      map(state => {
        // do something 
      })
    );
  }
  public getEventV2(): Observable<event[]> {
    return combineLatest(this.store.select(getEventStore), this.store.select(getEvents)).pipe(
      map(state => {
        // do something 
      })
    );
  }

My testing has the methods inside the providers:

    { provide: EventsService, useValue: { getEvent: () => of([])}},
    { provide: EventsService, useValue: { getEventV2: () => of([])}},
like image 309
Corcor Avatar asked Jul 09 '26 06:07

Corcor


1 Answers

The problem is Angular is using the last provider you have provided for EventsService.

To fix it, do this:

{ provide: EventsService, useValue: { getEvent: () => of([]), getEventV2: () => of([]) } },
// remove the two instances of EventsService and keep it to one.
like image 163
AliF50 Avatar answered Jul 11 '26 17:07

AliF50



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!