Cannot read property "subscribe" Angular Test Mock

I am trying to unit test an Angular component that has an injected service. In the constructor of the component, a method is called on the injected service, which returns an Observable. I'm trying to make fun of the service component in my unit test, but I'm working with this error: TypeError: Cannot read property 'subscribe' of undefined

.

I tried to mock the service in the following ways:

const serviceStub = {
  getObservable: () => { return {subscribe: () => {}}; },
};

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      {provide: MyService, useValue: serviceStub}
    ]
})


it('should create', () => {
  spyOn(serviceStub, 'getObservable').and.returnValue({subscribe: () => {}});
  expect(component).toBeTruthy();
});

      

It looks like I'm missing something obvious. Can anyone point this out?

UPDATE

I am getting this error even when I enter the actual service from my test bed providers.

The component constructor looks like this:

private _subscription: Subscription;

constructor(private _service: MyService) {
  this._subscription = _service.getObservable().subscribe(console.log);
}

      

+3


source to share


1 answer


Use the injection to inject the service and mock it with no stub

it('should create', inject([MyService], (myService: MyService) => {
  spyOn(myService, 'getObservable').and.returnValue({subscribe: () => {}});
  expect(component).toBeTruthy();
}));

      

Here's the full version:

component:



@Component({
  selector: 'my-cmp',
  template: 'my cmp {{x}}'
})
export class MyComponent {
  x;

  constructor(private myService: MyService) {
    this.myService.getObservable()
      .subscribe(x => {
        console.log(x);
        this.x = x;
      });
  }
}

      

Test:

   describe('my component test', () => {
    let fixture: ComponentFixture<MyComponent>, comp: MyComponent, debugElement: DebugElement, element: HTMLElement;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService]
      });
    }));

    beforeEach(() => {
      fixture = TestBed.createComponent(MyComponent);
      comp = fixture.componentInstance;
      debugElement = fixture.debugElement;
      element = debugElement.nativeElement;
    });

    it('should create', inject([MyService], (myService: MyService) => {
      expect(comp).toBeTruthy();
    }));

    it('should set value', async(inject([MyService], (myService: MyService) => {
      spyOn(myService, 'getObservable').and.returnValue(Observable.of(1));

      fixture.detectChanges();

      fixture.whenStable().then(() => {
        expect(comp.x).toEqual(1);
      });
    })));
  });

      

+2


source







All Articles