测试运行时未初始化Datepicker和Timepicker

时间:2019-01-03 14:45:49

标签: angular ngx-bootstrap angular-testing

在Angular应用中,我经常使用datepicker中的timepickerngx-bootstrap组件。

它们工作得很好,但是显然我无法对其进行测试。问题是当我的测试用例运行时,那些组件还没有初始化:

first line debugger

我在测试用例的第一行设置了断点。

当测试用例完成执行时,我可以看到datepicker和timepicker组件已正确初始化:

enter image description here

我的代码如下:

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

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [
        MyComponent,
        // ...
      ],
      imports: [
        BsDatepickerModule.forRoot(),
        TimepickerModule.forRoot(),
        // ...
      ],
      providers: [
        // ...
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.autoDetectChanges(true);
  });

  it('some expectation here', () => {
    // whatever I put here, at this line the datepicker and timepicker will NOT be initialised
  });
});

如何在我的测试用例运行后之后确认datepicker和timepicker组件已初始化?


编辑

我进行了更多调查,问题在于[(ngModel)]="time"元素中的<timepicker> 基本上只有在我的测试用例退出后才被触发。

如何手动触发它?

我尝试使用timepickerElement.dispatchEvent(new Event('input'));,但是它不起作用。

还尝试了fixture.detectChanges()fakeAsync + tick()等,但无法解决问题。

1 个答案:

答案 0 :(得分:0)

问题在于Datepicker和Timepicker的[(ngModel)]指令仅在执行测试用例之后才触发(因为我将它们包装到一个自定义组件中,然后将其用作表单控件)。 / p>

要触发该操作,我需要添加:

datetimeElement.dispatchEvent(new Event('change'));
timepickerElement.dispatchEvent(new Event('change'));
fixture.detectChanges();

在更改Datepicker和Timepicker元素的值之后。