在角项目中使用jasmine的单元测试订阅方法

时间:2018-02-06 12:02:54

标签: angular unit-testing jasmine subscribe

我尝试为subscribe方法的组件测试 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());
    });
});

测试套件

strtotime()

但抛出错误,因为&#34;无法监视订阅&#34;。这是测试订阅方法的过程。请建议。

1 个答案:

答案 0 :(得分:0)

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

  1. 来自&#39; rxjs / Observable&#39;的导入导入{Observable};在我的spec文件中
  2. 为内部订阅

    中的方法创建了一个间谍

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

  3. 3.Call ngOnInit()

    4.使用expect()方法

    进行断言