变量在运行jasmine测试时返回null

时间:2018-04-20 06:07:49

标签: angular jasmine karma-jasmine

我已经实现了jasmine测试并测试了我的方法。运行previousItem的测试值时为null。如果我将previousitem的值硬编码为20000000,则返回true,这很好。如何在我的测试中初始化previousitem值。

请注意,数组中的第一个元素将包含minSize:0和maxSize:20000000。

    isMinValid(currentItem: any, item_IDX: number) {
        if (item_IDX === 0) {
          return true;
        }

        let previousItem = this.domicileInfo.taxAssesment.items[item_IDX - 1];
        if (+currentItem.minSize !== +previousItem.maxSize  ) {
          return false;
        }
        return true;
      }


beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        TooltipModule.forRoot(),
        FormsModule,
        TranslateModule.forRoot({
          loader: { provide: TranslateLoader, useClass: TranslateFakeLoader }
        })
      ],
      providers: [
        { provide: BsModalRef, useClass: BsModalRefStub },
        { provide: BackendProxy.ReferenceProxy, useClass: ReferenceProxyStub },
        { provide: RunService, useValue: runServiceStub }
      ],
      declarations: [DomicileSelectionComponent, YesNoPipe, CLICK_INPUT_DIRECTIVE, ShortNumberFormatPipe]
    });
  });

     beforeEach(() => {
        fixture = TestBed.createComponent(DomicileSelectionComponent);
        comp = fixture.componentInstance;
        comp.domicileInfo =  domicileInformationDataResult.data;
        fixture.detectChanges();
      });


        fit('should return true because the current item min value is equal to the previous max value', () => {
            comp.domicileInfo.taxAssesment.items = [{maxSize: 30000000 , minSize: 20000000 , values: [2 , 2]}];
            let isMax: boolean = comp.isMinValid(comp.domicileInfo.taxAssesment.items[0] , 1);
            console.log(isMax);
            console.log(comp.domicileInfo.taxAssesment.items);
            expect(isMax).toBe(true);
          });

组件代码

import { Component, OnInit } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap';
import { Base } from '@wtw/toolkit';
import * as BackendDto from '../../../../api/dtos';
import * as BackendProxy from '../../../../api/proxies';
import { IModalConfirmation } from '@wtw/platform/interfaces';
import { TranslateService } from '@ngx-translate/core';
import * as Rx from 'rxjs/Rx';
import { RunService } from '@wtw/platform/services';
import { CONSTS } from '../../../../config';

const minCapRequirement = 'minCapReq';
const premuimTaxCap = 'premTaxCap';
@Component({
  selector: 'app-domicile-selection',
  templateUrl: './domicile-selection.component.html'
})
export class DomicileSelectionComponent extends Base.ReactiveComponent implements OnInit, IModalConfirmation {
  domicileInfo: BackendDto.DomicileInformation;
  public data: any;
  public onClose: Rx.Subject<boolean>;
  public active = false;
  public currentSelectedCurrency = '';
  public domicileId: number;
  public domiciles: BackendDto.Domicile[];
  public amendAssumptions: string;
  fieldCategories: typeof BackendDto.DynamicFieldCategory = BackendDto.DynamicFieldCategory;
  private domicile: BackendDto.Domicile;
  private _selectedIndustries: BackendDto.Industry[];

  constructor(
    private _bsModalRef: BsModalRef,
    private _refProxy: BackendProxy.ReferenceProxy,
    private _runs: RunService,
    private _translate: TranslateService

  ) {
    super();
  }

  public ngOnInit() {
    this.onClose = new Rx.Subject();
    return [this._runs.activeRun.subscribe(r => {
      this.currentSelectedCurrency = r.currencyInfo.currentSelectedCurrency;
    })];
  }

  public show() {
    this.domicileId = this.data.domicile.id;
    this.domicile = this.data.domicile;
    this.domiciles = this.data.domiciles;
    this._selectedIndustries = this.data.selectedIndustries;
    this.domicileInfo = this.domicile.domicileInformation;
    this.amendAssumptions = this._translate.instant('CAPTIVES.DOMICILES.AMENDASSUMPTIONS', { domicile: this.domicile.name });
    this.active = true;
  }

  public close() {
    this.hide(null);
  }

  public udpatevalue(item, value) {
    item.maxSize = value;
  }
  public ok() {
    this.data.domicileId = this.domicileId;
    this.data.domicileInfo = this.domicileInfo;
    this.hide(true);
  }

  public cancel() {
    this.hide(false);
  }

  isMinValid(currentItem: any, item_IDX: number) {
    if (item_IDX === 0) {
      return true;
    }
    debugger;
    let previousItem = this.domicileInfo.taxAssesment.items[item_IDX - 1];
    if (+currentItem.minSize !== +previousItem.maxSize  ) {
      return false;
    }
    return true;
  }


  isMaxValid(currentItem: any, item_IDX: number) {
    if (item_IDX === 0) {
      return true;
    }

    if (+currentItem.maxSize <= +currentItem.minSize ) {
      return false;
    }
    return true;
  }

  domicileChanged($event) {
    if (this.domicileId === this.domicile.id) {
      this.domicileInfo = this.domicile.domicileInformation;
    } else {
      this._loadInformation();
    }
  }

  private _loadInformation() {
    this._refProxy.getDefaultDomicileInformationForClient(this.domicileId, this._selectedIndustries[0].id)
      .uiSignal('infos')
      .subscribe(ret => {
        this.domicileInfo = ret.data;
        const domicileName = this.domiciles.find(x => x.id === this.domicileId).name;
        this.amendAssumptions = this._translate.instant('CAPTIVES.DOMICILES.AMENDASSUMPTIONS', { domicile: domicileName });
      });
  }


  private hide(nextVal?: boolean) {
    this.active = false;
    this.onClose.next(nextVal);
    this._bsModalRef.hide();
  }

  get addnDomicileDetailMinCapReq(): BackendDto.DomicileAddnDetail {
    return this.domicileInfo.addnDomcileDetails.find(x => x.fieldInfo.key === minCapRequirement);
  }

  get addnDomicileDetailPremuimTaxCap(): BackendDto.DomicileAddnDetail {
    return this.domicileInfo.addnDomcileDetails.find(x => x.fieldInfo.key === premuimTaxCap);
  }

  get maxCurrency() {
    return CONSTS.general.maximumCurrencyValue;
  }
}

1 个答案:

答案 0 :(得分:0)

您错过了fixture.detectChanges();

我希望以下解决方案能解决您的问题。

fit('should return true because the current item min value is equal to the previous max value', () => {
    comp.domicileInfo.taxAssesment.items = [{maxSize: 30000000 , minSize: 20000000 , values: [2 , 2]}];
    fixture.detectChanges();
    let isMax: boolean = comp.isMinValid(comp.domicileInfo.taxAssesment.items[0] , 1);    
    expect(isMax).toBe(true);
  });

编辑:

你也错过了在testbed中配置测试模块。请查看以下内容

beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [YourModules],
            declarations: [YourComponent],
            providers: [
                { provide: CreateVersionService, useClass: MockCreateVersion }//providers
            ]
        });
        fixture = TestBed.createComponent(DomicileSelectionComponent);
        comp = fixture.componentInstance;
        comp.domicileInfo = domicileInformationDataResult.data;
        fixture.detectChanges();
    });