如何正确测试角材组件?

时间:2019-03-31 05:04:33

标签: angular unit-testing angular-material

我正在尝试使用mat-error,基本上,如果该字段为null,它只会显示一条错误消息。我已经使用ng-serve对其进行了手动测试,并且确实可以正常工作,但是当html元素出现时,我很难获取它。这是我的代码:

<mat-form-field>
  <input type="number" matInput placeholder="Gain or Loss" class="gain-or-loss-input-field" [formControlName]="'gainOrLoss'">
  <mat-error *ngIf="entryForm.controls.gainOrLoss.errors && entryForm.controls.gainOrLoss.errors.required"
             class="gain-or-loss-required-error-message">
    Gain or Loss is <strong>required</strong>.
  </mat-error>
</mat-form-field>

// other code here...

<button mat-raised-button color="primary" class="add-report-button" (click)="addEntry()">Add Report</button>

这是我的测试结果:

  let component: AddReportModalComponent;
  let fixture: ComponentFixture<AddReportModalComponent>;
  let pageDebug: DebugElement;
  let pageElement: HTMLElement;
  let entryService: EntryService;
  let entryServiceSpy: any;

  beforeEach(async(() => {
    entryServiceSpy = jasmine.createSpyObj('EntryService', [
      'fetchEntriesByStartDateEndDateAndCompany',
      'addEntry'
    ]);

    TestBed.configureTestingModule({
      declarations: [ AddReportModalComponent ],
      imports: [
        MatFormFieldModule,
        MatDatepickerModule,
        MatOptionModule,
        MatSelectModule,
        MatDialogModule,
        MatNativeDateModule,
        MatInputModule,
        BrowserAnimationsModule
      ],
      providers: [
        { provide: MatDialogRef, useValue:{}},
        { provide: EntryService, useValue: entryServiceSpy },
        { provide: DateService, useValue:{}}
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
        NO_ERRORS_SCHEMA
      ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(AddReportModalComponent);

      pageDebug = fixture.debugElement;
      pageElement = pageDebug.nativeElement;

      entryService = pageDebug.injector.get(EntryService);
      component = fixture.componentInstance;

      fixture.detectChanges();
    });
  }));

  it('should display an error message if Gain or Loss field is null when the form is submitted.', async(() => {
    component.entryForm.controls.gainOrLoss.setValue(null);

    const addReportButton = pageDebug.query(By.css(addReportButtonSelector));
    addReportButton.nativeElement.click();

    fixture.detectChanges();

    fixture.whenStable().then(() => {
      const requiredErrorElement = pageDebug.query(By.css('.gain-or-loss-required-error-message'));
      expect(requiredErrorElement.nativeElement.innerText).toEqual('Gain or Loss is required.');
    });

  }));

这是我遇到的错误:

Failed: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of null
TypeError: Cannot read property 'nativeElement' of null
    at http://localhost:9876/_karma_webpack_/webpack:/src/app/stockmarket/portfolio/views/add-report-modal/add-report-modal.component.spec.ts:127:35
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:391:1)
    at AsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.AsyncTestZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:714:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:286:1)
    at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:390:1)
    at Zone../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:150:1)

当我运行ng-test时,我注意到没有一个实际的动画起作用。当我使用简单的divngIf进行测试时,测试通过了,但是当我使用角形材料时失败了。

我尝试添加console.log来查看element(.gain-or-loss-required-error-message)是否确实存在,但是它只是null。所有动画都不起作用,这正常吗?

我记得在另一个项目中,我们正在使用引导程序,并且我的测试是单击按钮并显示正确的错误消息,这不是很复杂,甚至在运行测试时会触发动画。抱歉,也许我只是想念一些东西。我还尝试了将BrowserAnimationsModule导入我的TestBed imports中,因为我认为可能我无法拾取该元素的原因是动画没有触发,但实际上并没有执行任何操作。抱歉,我想念什么?

0 个答案:

没有答案