在 angular 项目中使用 jasmine 进行单元测试订阅方法

Unit testing subscribe method using jasmine in angular project

我正在尝试为具有 subscribe 方法的组件测试 ngOnInit() 方法:

分量:

 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
        }));
            }
        }   
    }

测试套件

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());
    });
});

但抛出错误 "cannot spy on subscriptions"。这是测试订阅方法的程序吗?请提出建议。

已通过如下所示实现代码修复:

  1. 已从 'rxjs/Observable' 导入 import { Observable };在我的规范文件中
  2. 为订阅内部调用的方法创建了一个间谍

    spyOn(component.subscriptions, "push");<br> const spy = spyOn(sharedDataService, 'getModel').and. returnValue(Observable.of(“订阅方法要返回的数据”);

3.Call ngOnInit()

4.Make 使用 expect() 方法的断言