简体   繁体   English

茉莉花测试时变量返回null

[英]variable returning null while running jasmine test

I have implemented jasmine test and testing my method.While running the test values of previousItem is null. 我已经实现了茉莉花测试并测试了我的方法,而运行previousItem的测试值为null。 If i hardcode the value of previousitem to 20000000, it returns true which is fine. 如果我将preiteitem的值硬编码为20000000,则返回true,这很好。 How do i initialize previousitem value in my test. 我如何在测试中初始化previousitem值。

Please note the the first element in the array would contain minSize : 0 and maxSize: 20000000. 请注意,数组中的第一个元素将包含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);
          });

Component code 组件代码

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

You have missed fixture.detectChanges(); 您错过了fixture.detectChanges(); .

I hope this below solution will solve your problem. 我希望下面的解决方案能够解决您的问题。

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

edit: 编辑:

And also you have missed to configure the testing module in testbed. 而且您也错过了在测试平台上配置测试模块的步骤。 So check this below 所以在下面检查一下

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

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

相关问题 运行jasmine测试用例时模板变量抛出未定义的错误 - Template variable throwing undefined error while running jasmine test case 组件集成测试,茉莉花间谍返回可订阅 - Component integration test with jasmine spy returning Subscribable 未找到 Angular 返回路线上的 Jasmine 单元测试 - Jasmine unit test on Angular returning route not found 使用茉莉花和业力进行测试时,未在测试规范中定义声明的全局范围变量 - Global scope Variable declared is not defined in test spec while testing using jasmine and karma 在 Angular 应用程序中运行 ng 测试时出现空注入器错误 - Getting the null injector errors while running ng test in angular application angular jasmine 测试中的 mocking 时出错 - error while mocking in angular jasmine test 是否可以在茉莉花测试中获取模板引用变量? - Is it possible to get template reference variable in jasmine test? 茉莉花测试找不到导入的变量 - Jasmine test cannot find imported variable “你的一些测试做了一个完整的页面重新加载!” 在 angular 14 应用程序中运行 karma jasmine 单元测试用例时出错 - "Some of your tests did a full page reload!" error while running karma jasmine unit test cases in angular 14 application Angular2 jasmine 测试失败,内联模板:0:0 导致:null 不是对象 - Angular2 jasmine test fails with inline template:0:0 caused by: null is not an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM