TypeError:无法读取未定义的属性“ show”

时间:2019-04-04 07:31:05

标签: javascript angular jasmine ngx-bootstrap

我正在用角度7编写ngx-bootstrap(bsDateRangePickerDirective)的测试用例,但是当我尝试从规格文件中打开bsdaterangePickerDirective实例时,出现了无法读取未定义属性显示的错误。

以下是我编写的代码:

component.ts文件

@ViewChild("sdp") sdatepicker: BsDaterangepickerDirective;
// Function
openDatePicker() {
    this.sdatepicker.show();
  }

Component.spec.ts文件

import { ComponentFixture, async, TestBed } from "@angular/core/testing";
import { NO_ERRORS_SCHEMA } from "@angular/core";
import { NameComponent } from "./name-box.component";
import { FormsModule } from "@angular/forms";
import { BsDatepickerModule, BsDaterangepickerDirective } from "ngx-bootstrap";
import { HttpClientTestingModule } from "@angular/common/http/testing";

describe('NameComponent', () => {
  let fixture: ComponentFixture<SearchBoxComponent>;
  let component: SearchBoxComponent;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [NameComponent],
      imports: [
        FormsModule,
        BsDatepickerModule,
        HttpClientTestingModule
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NameComponent);
    component = fixture.componentInstance;

  });


  it('Should open date picker', () => {
    const dateSpy = spyOn(BsDaterangepickerDirective.prototype, "show").and.returnValue(true);
    component.openDatePicker('sdatepicker');
    expect(dateSpy).toHaveBeenCalled();
  });

});

组件模板文件:

<div class="grid-search-datepicker date-selector">
      <input type="text" class="form-control" id="start-date-selector_{{searchTableId}}" [(ngModel)]="dateRange.startDate"
        bsDatepicker #sdp="bsDatepicker" (onHidden)="updateMinEndDate()" [bsConfig]="startDateConfig" placeholder="{{l10n.fromdate}}"
        readonly>
      <i class="icon-small-calendar text-blue open-datetimepicker" (click)='openDatePicker("sdatepicker")' aria-hidden="true"></i>
    </div>

1 个答案:

答案 0 :(得分:0)

在模板中,您正在使用bsDatepicker,但在组件中,您将其称为BsDaterangepickerDirective。我认为,如果将模板更改为:

<div class="grid-search-datepicker date-selector">
  <input type="text" class="form-control" id="start-date-selector_{{searchTableId}}" 
    [(ngModel)]="dateRange.startDate"
    bsDaterangepicker
    #sdp="bsDaterangepicker"
    (onHidden)="updateMinEndDate()"
    [bsConfig]="startDateConfig"
    placeholder="{{l10n.fromdate}}"
    readonly
  >
  <i class="icon-small-calendar text-blue open-datetimepicker" 
    (click)='openDatePicker("sdatepicker")'
    aria-hidden="true"
  >
  </i>
</div>

请参阅:https://stackblitz.com/edit/angular-sgaq4e