2

I'm trying to test ngOnInit() method for the component that has a subscribe method:

Component:

 import { Component, OnInit} from '@angular/core';
 import { SharedDataService } from './../services/shared-data.service';

     @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
        constructor(private sharedDataService: SharedDataService,) { }
        this.subscriptions = [];

        ngOnInit() {      

   this.subscriptions.push(this.sharedDataService.getModel().subscribe(model => {
             this.message=model.message
        }));
            }
        }   
    }

Test Suite

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {  XHRBackend } from '@angular/http';

describe('AppComponent Test', () => {
    let component: any;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async(() => {
         TestBed.configureTestingModule({
            declarations: [AppComponent],
        providers: [SharedDataService , { provide: XHRBackend, useClass: MockBackend }]

        })
            .compileComponents();
    }));
    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    it('should be created', () => {
        expect(component).toBeTruthy();
    });
    it('test onInit function', () => {
        component.ngOnInit();
        spyOn(component.subscriptions,"push");
        expect(component.subscriptions).toHaveBeenCalledWIth(component.sharedDataService.getModel());
    });
});

But throwing error as "cannot spy on subscriptions".Is this is the procedure to test subscribe method. Please suggest.

1 Answer 1

3

Fixed by implementing code as shown below:

  1. Imported import { Observable } from 'rxjs/Observable'; in my spec file
  2. Created a spy for the method called inside subscription

    spyOn(component.subscriptions, "push");
    const spy = spyOn(sharedDataService, 'getModel').and. returnValue(Observable.of(“data to be returned by subscribe method”);

3.Call ngOnInit()

4.Make assertions using expect() method

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.