【问题标题】:Angular matInput not updating component property with two-way binding in Jasmine unit testAngular matInput 未在 Jasmine 单元测试中使用双向绑定更新组件属性
【发布时间】:2022-07-30 08:15:58
【问题描述】:

我有一个matInput 用于更新组件属性:

<input matInput [(ngModel)]="componentProperty" />
<div>componentProperty value is: {{ componentProperty }}</div>

当我使用它时,它会起作用:显示的 componentProperty 值与我放入框中的值匹配。

但是,我为此编写的单元测试不起作用:

    it('should update componentProperty to match input box value', async () => {
        const inputHarness = await loader.getHarness(
            MatInputHarness
        );
        const testValue = 'hello';

        expect(component.componentProperty).toEqual('');
        await inputHarness.setValue(testValue);
        expect(component.componentProperty).toEqual(testValue);
    });

这失败了 Expected '' to equal 'hello'. 给出了什么?

【问题讨论】:

    标签: angular angular-material jasmine


    【解决方案1】:

    这里的线索是控制台错误信息:Can't bind to 'ngModel' since it isn't a known property of 'input'.

    问题在于测试的设置:我们没有导入正确的模块。我们需要添加到我们的测试设置中:

    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        MatFormFieldModule,
        MatInputModule,
        NoopAnimationsModule,
      ],
      ...
    });
    

    理解测试失败的方法是:我们实际上并没有将输入框绑定到组件属性,因为测试框架不知道matInput是什么,因此不知道如何处理ngModel。我们需要通过导入相关模块来告诉它如何处理matInput

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 2019-01-28
      • 2020-06-28
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2022-01-09
      • 2018-12-09
      相关资源
      最近更新 更多