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

Angular test 'subscribe is not a function'

In my component inside ngOnInit I have a subscribe() inside which I call a component function:

ngOnInit(): void {
    this.navigationService.itemReset$.subscribe(event => this.resetItem(event));
}

in the navigationService I have:

btnPressed$: Subject<Event> = new Subject();
itemReset$: Observable<Event> = this.btnPressed$.asObservable();

keyDown(event: Event): void {
  this.btnPressed$.next(event);
}

I searched a lot about this issue, and tried something like this in my component test:

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

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let navigationServiceMock = {
    itemReset$: () => of({} as Event),
    // tried this: itemReset$: jasmine.createSpy('itemReset$').and.returnValue(of({})),
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [{
        provide: navigationService,
        useValue: navigationServiceMock
      }]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

but still, get the error

TypeError: this.navigationService.itemReset$.subscribe is not a function

Any idea, why it doesn’t work?
I would be really grateful for any help!

>Solution :

Ensure that the type of itemReset$ in your fake object matches the type in the implementation.

You need to pass a Observable<Event> but you had a function returning such an observable instead.

let navigationServiceMock = {
    itemReset$: of({} as Event),
};
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