Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'subscribe') of subscribe inside ngOnInit with unit test

Currently facing a unit test errror:

AppComponent > should call app
TypeError: Cannot read properties of undefined (reading 'subscribe')

Inside my ngOnInit I have:

this.eventsService.currentEvents.subscribe(events => {
  this.events = events;
  return this.processEvents(this.events);
});

The test where it fails is here (where ngOnInit is called):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  it(`should call app`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    app.ngOnInit();
  });

And my events service is:

export class EventsService {
  constructor(private http: HttpClient, private store: Store<AppState>) {}
  
  private eventsSource = new BehaviorSubject<any>([]);
  currentEvents: Observable<any> = this.eventsSource .asObservable();
  
  getEvents(events: []) {
   this.eventsSource.next(events);
  }
}

The app.component.spec has this set up as well:

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientModule],
      declarations: [AppComponent],
      providers: [
        { provide: EventsService , useValue: {
          getEvents: () => of([]),
          processEvents: () => of([])
        }},
        provideMockStore({}),
        { provide: Angulartics2, useValue: {} },
        { provide: Angulartics2GoogleAnalytics, useValue: { startTracking: () => {}} },
        { provide: WindowRef }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    eventService = TestBed.inject(EventsService);
    (<any>window).ga = jasmine.createSpy('ga');
  });

>Solution :

In the EventService provider, add the service property currentEvents too.

providers: [
  {
    provide: EventsService, useValue: {
      getEvents: () => of([]),
      processEvents: () => of([]),
      currentEvents: of('events')
    }
  },
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading