在角项目中使用jasmine的单元测试订阅方法 [英] Unit testing subscribe method using jasmine in angular project

查看:348
本文介绍了在角项目中使用jasmine的单元测试订阅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

组件:

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

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

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

推荐答案

通过实现如下所示的代码来解决:

Fixed by implementing code as shown below:


  1. 从'rxjs / Observable'导入导入{Observable};在我的规范文件中

  2. 为订阅内部的方法创建了一个间谍

  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')。和。
returnValue(Observable.of(订阅方法返回的数据);

3.Call ngOnInit()

3.Call ngOnInit()

4.使用 expect()方法进行断言

4.Make assertions using expect() method

这篇关于在角项目中使用jasmine的单元测试订阅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆