【问题标题】:Angular test template driven form written in material用材料编写的角度测试模板驱动形式
【发布时间】:2018-04-16 11:30:50
【问题描述】:

我正在尝试为我的组件编写测试。我的组件有一个表单,其中有一个下拉(mat-select)字段,上面有必需的属性。

如果我在其中设置一个值,则表单有效:

我该如何测试。我想编写一个测试,期望 form.invalid 在我设置值之前是真实的,而 form.valid 在设置值之后是真实的。

it('should validate the app', () => {
let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    fixture.detectChanges();
    let component = fixture.componentInstance;
    expect(component.form.invalid).toBeTruthy();
    component.myobject.value = "ABC";
    expect(component.form.valid).toBeTruthy();

  });
});

如果测试看起来像上面那样,在代表我的字段的表单对象上找到的 ngModel 几乎没有变化。

如果我在设置值后添加fixture.detectChanges()(不确定何时调用此方法),字段的模型将为“ABC”,但字段的值为“”:

it('should validate the app', () => {
let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    fixture.detectChanges();
    let component = fixture.componentInstance;
    expect(component.form.invalid).toBeTruthy();
    component.myobject.value = "ABC";
    fixture.detectChanges();
    expect(component.form.valid).toBeTruthy();

  });
});

我的感觉是 mat-select 字段没有正确启动,它还没有计算出有哪些有效选项。如果我调试并检查 dom,则在设置值时没有绘制任何选项。

有人知道怎么解决吗?

如果有人想克隆并尝试,我做了一个简单的 github repo:

https://github.com/trashhead/angular-templ-drivn-form-test

【问题讨论】:

    标签: angular testing jasmine angular-material


    【解决方案1】:

    我找到了一种现在似乎可行的方法。我只是不明白运行 whenStable 时会发生什么。

    it('This one works', (done) => {
      let fixture = TestBed.createComponent(AppComponent);
      fixture.detectChanges();
      fixture.whenStable().then(() => {
        fixture.detectChanges();
        let component = fixture.componentInstance;
        expect(component.form.invalid).toBeTruthy();
        component.myobject.value = "ABC"; 
        fixture.detectChanges();
        fixture.whenStable().then(() => {
          fixture.detectChanges();
          expect(component.form.valid).toBe(true);
          done();
        })
      });
    });
    

    所以解决方案是,在设置下拉值之后,我必须执行另一个 whenStable 并在其中检查表单的有效性。

    【讨论】:

    • 我错过了第二个fixture.whenStable
    【解决方案2】:

    你试过了吗:

    expect(component.form.invalid).toBe(true) 接下来 expect(component.form.valid).toBe(true)?

    【讨论】:

    • 遗憾的是没有区别
    • 所以你的测试日志说:“expect undefined toBe true”?
    • 如果我有 .toBeTruthy();我得到“预期虚假是真实的”。如果我有 .toBe(true) 我会得到“预期的假是真的”。
    猜你喜欢
    • 2018-11-25
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2017-08-11
    • 2020-07-24
    • 2022-11-25
    • 2015-06-11
    • 2020-02-29
    相关资源
    最近更新 更多