簡體   English   中英

如何閱讀 Angular 單元測試中的訂閱?

[英]How to read subscribe in Angular Unit Test?

我正在嘗試編寫組件的測試用例,起初我試圖檢查基本測試用例是否有效。 在那里我遇到了一些與依賴注入相關的錯誤並解決了這些錯誤。 現在我面臨的第一個問題是 mocking API 調用。

以下是我正在為其編寫測試用例的組件代碼:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClientService } from '@service/http-client.service';
import { CustomErrorStateMatcher } from '@validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-prep-card',
  templateUrl: './prep-card.component.html',
  styles: ['legend { width: fit-content !important; }']
})
export class PrepCardComponent implements OnInit {

  constructor(private fb: FormBuilder, private _http: HttpClientService, private toastr: ToastrService) { }
  
  foamTypeList: string[] = [];
  colorList: string[] = [];
   
  ngOnInit() { this.getFoam_ColorList() }

  private getFoam_ColorList() {
    this._http.getFoamType_ColorList('ABC').subscribe(response => {
      this.foamTypeList = response.data.foamTypesAndColors.foamTypes;
      this.colorList = response.data.foamTypesAndColors.colors;
    });
  }
}

起初,我嘗試運行一個簡單的測試用例來檢查它是否工作正常。 下面是我寫的測試用例:

import { ComponentFixture, inject, TestBed } from "@angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientService } from "@service/http-client.service";
import { ToastrService } from "ngx-toastr";
import { MaterialModule } from "src/app/material/material.module";
import { PrepCardComponent } from "./prep-card.component";

describe('PrepCardComponent', () => {
    let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>,
        _httpSpy: jasmine.SpyObj<HttpClientService>, _toastrSpy: jasmine.SpyObj<ToastrService>;

    beforeEach(async () => {
        const _httpSpyObj = jasmine.createSpyObj('HttpClientService', ['getFoamType_ColorList']),
            _toastrSpyObj = jasmine.createSpyObj('ToastrService', ['success', 'error']);

        await TestBed.configureTestingModule({
            declarations: [PrepCardComponent],
            imports: [
                RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
            ],
            providers: [
                { provide: HttpClientService, useValue: _httpSpyObj },
                { provide: ToastrService, useValue: _toastrSpyObj },
            ]
        }).compileComponents();
        fixture = TestBed.createComponent(PrepCardComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('test', () => expect('a').toBe('a'));
});

上面的代碼片段拋出了以下錯誤:

TypeError:無法在 PrepCardComponent.getFoam_ColorList (http://localhost:9876/karma_webpack/ webpack :/src/app/pages/prep-card/prep-card.component.ts:57 讀取未定義的屬性(讀取“訂閱”) :52) 在 PrepCardComponent.setFormFieldValidator (http://localhost:9876/ karma_webpack /webpack:/src/app/pages/prep-card/prep-card.component.ts:65:10) 在 PrepCardComponent.createForm (http: //localhost:9876/ karma_webpack /webpack:/src/app/pages/prep-card/prep-card.component.ts:48:10) 在 PrepCardComponent.ngOnInit (http://localhost:9876/ karma_webpack /webpack: /src/app/pages/prep-card/prep-card.component.ts:28:10) 在 callHook (http://localhost:9876/ karma_webpack /webpack:/node_modules/@angular/core/fesm2015/core. mjs:2542:1) 在 callHooks (http://localhost:9876/karma_webpack/ webpack :/node_modules/@angular/core/fesm2015/core.mjs:2511:1) 在 executeInitAndCheckHooks (http://localhost:9876/ karma_webpack /webpack:/node_modules/@angular/core/fesm2015/core.mjs:2462:1) 在 refreshView (http:// localhost:9876/ karma_webpack /webpack:/node_modules/@angular/core/fesm2015/core.mjs:9499:1) 在 renderComponentOrTemplate (http://localhost:9876/ karma_webpack /webpack:/node_modules/@angular/core/fesm2015 /core.mjs:9598:1) 在tickRootContext (http://localhost:9876/ karma_webpack /webpack:/node_modules/@angular/core/fesm2015/core.mjs:10829:1)

為了解決這個問題,我在這里搜索了不同的問題,並看到了下面提到的常見解決方案以獲得observable

it('Call Service', inject([HttpClientService], (_http: HttpClientService) => {
    spyOn(_http, 'getFoamType_ColorList').and.returnValue({subscribe: () => {}})
}));

編寫上述測試用例在subscribe position 中引發錯誤(如下所述)。

類型 'void' 不可分配給類型 'Subscription'.ts(2322)

服務代碼

getFoamType_ColorList(cardType: string) {
  return this.http.get<{ message: string, data: { foamTypesAndColors: { foamTypes: string[], colors: string[] } } }>
    (`${this.URL}/validate/foam-type-and-color/${cardType}`);
}

誰能幫我解決這個問題?

我會建議這個:

import { of } from 'rxjs';
spyOn(httpclientservice, 'getFoamType_ColorList').and.returnValue(of(YOUR VALUE));

試試這個也許

spyOn(_http,'getFoamType_ColorList').and.returnValue(Observable.of(Your_Value));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM