Unit testing subscribe method using jasmine in angular project

余生颓废 提交于 2019-12-13 03:37:37

问题


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:


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



来源:https://stackoverflow.com/questions/48642641/unit-testing-subscribe-method-using-jasmine-in-angular-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!