使用 MatInputHarness 测试负数

Test a negative number with MatInputHarness

我一直在寻找关于这个主题的解决方案,并且有一个已解决的错误票:https://github.com/angular/components/issues/19314

但是,当将值设置为 -1.[=24 时,我仍然无法使用 type="number"、使用 MatInputHarness 来测试 matInput =]

这里是尽可能简化的示例代码(Stackblitz):

app.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <form [formGroup]="form">
      <mat-form-field>
        <mat-label>Number input</mat-label>
        <input
          matInput
          type="number"
          formControlName="numberInput"
          name="numberInput"
        />
      </mat-form-field>
    </form>
  `,
})
export class AppComponent {
  public form: FormGroup = new FormGroup({ numberInput: new FormControl() });
}

app.component.spec.ts

import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatInputHarness } from '@angular/material/input/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';

let fixture: ComponentFixture<AppComponent>;
let loader: HarnessLoader;

describe('PatientsEnrollComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        NoopAnimationsModule,
        MatInputModule,
        MatFormFieldModule,
      ],
      declarations: [AppComponent],
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    loader = TestbedHarnessEnvironment.loader(fixture);
  });

  it('should be marked as invalid', async () => {
    let numberInputHarness = await loader.getHarness(
      MatInputHarness.with({ selector: "[name='numberInput']" })
    );
    let numberInputControl =
      fixture.componentInstance.form.controls['numberInput'];

    await numberInputHarness.setValue('-1');
    // Here it fails, since value is actually set to '1'.
    expect(numberInputControl.value).toBe('-1');
  });
});

结果

当运行 npm run test时,测试失败,错误消息为Expected 1 to be '-1',意思是实际设置的值是1,而不是-1正如我指出的那样。

我在这里做错了什么?非常感谢!

已修复 Material 13.3.2.via https://github.com/angular/components/commit/e9734a9c663b0e462e5c3d8ba2126a87aeeb3191.

如果你这样做

await numberInputHarness.setValue('-1');

expect(numberInputControl.value).toBe(-1);

现在有效