簡體   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