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

时间:2019-03-21 00:35:42

标签: angular jasmine angular-material karma-jasmine

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

  

预期''为“测试名称”。

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

这是我的某些节点模块的版本:

  • 角度7.2.8
  • 材料7.3.3
  • 业力4.0.1
  • 茉莉核3.3.0
  • 业力茉莉花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',
    );
  });
});

1 个答案:

答案 0 :(得分: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