繁体   English   中英

使用 Jasmine/Karma 对组件中的订阅方法进行单元测试

[英]Unit test for a subscribe method in a component with Jasmine/Karma

我想用组件中的 ngOnInit 调用的 subscribe 测试方法。 此方法称为 getPagesJson,定义在 getjsonService 中,并从 JSON 文件中获取一个值。

我的测试的目标 - 使用存根为 getPagesJson 赋予一些价值,并通过测试过程将其与原始数据进行比较。

订阅单元测试不起作用。 下面的代码:

第一个block.component.ts

import { Component, OnInit } from '@angular/core';
import { GetJsonService } from '../../services/get-json.service';

@Component({
  selector: 'app-first-block',
  template: '<h1 class="page-title">{{h1}}</h1>',
  styleUrls: ['./first-block.component.css']  
})

export class FirstBlockComponent implements OnInit {

  h1:any;

  constructor(private getjsonService: GetJsonService) { }

  ngOnInit() {
    this.getjsonService.getPagesJson()
    .subscribe(
      data => this.h1=data["index"][0]["h1"],
      error => console.log(error)
    );
  }
}

获取-json.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import { PagesInt } from '../interfaces/pages-int';

@Injectable({
  providedIn: 'root'
})
export class GetJsonService {

    // Error handler
    private handleError(error: HttpErrorResponse) {
      if (error.error instanceof ErrorEvent) {
        console.error('Error message:', error.error.message);
      } else {  
        console.error(
          `Code from backend ${error.status}, ` +
          `Error: ${error.error}`);
      }
      return throwError(
        'Something is wrong');
    };

    constructor(private http: HttpClient) { }

    getPagesJson() {
      return this.http.get<PagesInt>('/assets/from-server/pages.json')
      .pipe( 
        retry(3), 
        catchError(this.handleError)
      );    
    }     
}

pages-int.ts

export interface PagesInt {
    h1:string;
    videoUrl?:string;
}

first-block.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { of, Observable } from "rxjs";

import { FirstBlockComponent } from './first-block.component';
import { GetJsonService } from '../../services/get-json.service';

describe('FirstBlockComponent', () => {
  let component: FirstBlockComponent;
  let fixture: ComponentFixture<FirstBlockComponent>;
  let spy: jasmine.Spy;
  let getjson: GetJsonService;

  const getJsonStub = {
    getPagesJson() {
      const data = [{h1: 'H1 with "Value"'}];
      return of( data );
    }
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FirstBlockComponent ],
      providers: [ 
        { provide: GetJsonService, useValue: getJsonStub } 
      ]
    })
    .compileComponents();
    getjson = TestBed.get(GetJsonService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FirstBlockComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
// Errors:
// Uncaught TypeError: Cannot read property '0' of undefined thrown


  it('should called getPagesJson', async(() => {
    spy = spyOn(getjson, 'getPagesJson');
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(spy).toBeTruthy(); 
    });
  }));
// Errors:
// Failed: Cannot read property '0' of undefined


// I'm using very simple and non asynchronous approach below
  it('should get H1 by getJsonService.getPagesJson()', () => {
    getjson.getPagesJson(); 
    fixture.detectChanges();
    expect(component.h1).toBe('H1 with "Value"');
  });
// Errors:
// Uncaught TypeError: Cannot read property '0' of undefined thrown
// Expected undefined to be 'H1 with "Value"'.


});

测试告诉你出了点问题,这很好。 您评论中的错误可以准确地告诉您问题所在。

Cannot read property '0' of undefined是说它找不到未定义的0 因此这部分失败了: data["index"][0] ,如果在 undefined 上找不到0 ,那么data["index"]必须是undefined

first-block.component.ts内,订阅设置this.h1=data["index"][0]["h1"]然后你在测试中将其模拟为const data = [{h1: 'H1 with "Value"'}]; . 这些不匹配。 相反,您应该在测试中包含const data = {index: [{h1: 'H1 with "Value"'}]}; - 这可能是为数据 model 创建接口的好机会,因为您遇到了它作为问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM