表单未在单元测试中填充组件的属性

问题描述 投票:0回答:1

我有一个组件,其中包含从容器传入的office对象。此对象中的属性填充一个表单,该表单在浏览器中按预期工作,但是如果我在单元测试中将模拟数据分配给此对象并检查其中一个输入的值,则显然为空。在我下面的测试中,前两个断言通过,但是我收到第3个以下错误消息:

预计''将成为'测试名称'。

我尝试添加一个fakeAsync包装,然后在我做tick()之前使用了fixture.detectChanges(),但这也没有用。为什么输入不是像office那样用浏览器中的数据填充?

以下是我的一些节点模块的版本:

  • 角度7.2.8
  • 材料7.3.3
  • 业力4.0.1
  • 茉莉核心3.3.0
  • karma-jasmine 2.0.1

component.ts:

export class FormComponent {
  @Input() office: Office;
  @Input() officeLoading: boolean;

  ...
} 

component.html:

<form *ngIf="!officeLoading" (ngSubmit)="saveForm(form)" #form="ngForm" novalidate>
  <mat-form-field>
    <input
      class="company-name"
      matInput 
      placeholder="Company Name" 
      type="text"
      name="companyName"
      required
      #companyName="ngModel"
      [ngModel]="office?.companyName">
    <mat-error *ngIf="companyName.errors?.required && companyName.dirty">
      Company name is required
    </mat-error>
  </mat-form-field>
 ...
</form>

component.spec.ts

describe('FormComponent', () => {
  let component: FormComponent;
  let fixture: ComponentFixture<FormComponent>;
  let el: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        BrowserAnimationsModule,
        FormsModule,
        MatInputModule,
        OverlayModule,
        StoreModule.forRoot({}),
      ],
      declarations: [FormComponent],
      providers: [Actions, MatSnackBar, Store],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FormComponent);
    component = fixture.componentInstance;
    el = fixture.debugElement;
    component.office = null;
    component.officeLoading = false;
    fixture.detectChanges();
  });

  it('should fill out form based on what comes back from API', () => {
    expect(component.office).toBe(null);
    expect(el.query(By.css('input.company-name')).nativeElement.value).toBe('');
    component.office = {
      companyName: 'Test Name',
    };
    component.officeLoading = false;
    fixture.detectChanges();

    expect(el.query(By.css('input.company-name')).nativeElement.value).toBe(
      'Test Name',
    );
  });
});
angular jasmine angular-material karma-jasmine
1个回答
1
投票

调用fixture.detectChanges()后,你需要等待灯具稳定。

 fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(el.query(By.css('input.company-name')).nativeElement.value).toBe(
        "Test Name",
      );
    });

Stackblitz

https://stackblitz.com/edit/directive-testing-yxuyuk?embed=1&file=app/app.component.spec.ts

© www.soinside.com 2019 - 2024. All rights reserved.