开玩笑,测试验证错误组件

时间:2019-10-10 09:19:14

标签: angular angular8 angular-test angular-jest

我正在尝试测试验证消息ts文件。但出现错误

Cannot find name 'control'.

但是我无法解决此问题。有人帮我吗?

这是我的组件ts文件:

import { Component, Input } from '@angular/core';
import { ValidationService } from './../../services/validation.service';

@Component({
    selector: 'control-messages',
    templateUrl: './control-messages.component.html',
    styleUrls: ['./control-messages.component.css']
})
export class ControlMessagesComponent {

    @Input() control: any;
    constructor() { }

    get errorMessage() {
        for ( const propertyName in this.control.errors ) {
            if (this.control.errors.hasOwnProperty(propertyName) && (this.control.dirty || this.control.touched)) {
                return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
            }
        }
        return null;
    }

}

这是我的测试规格文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ControlMessagesComponent } from './control-messages.component';
import { ValidationService } from './../../services/validation.service';

describe('ControlMessagesComponent', () => {
  let component: ControlMessagesComponent;
  let fixture: ComponentFixture<ControlMessagesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ControlMessagesComponent ],
      imports: [FormsModule, ReactiveFormsModule],
      providers: [
        { provide: ValidationService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ControlMessagesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

这是错误:

 TypeError: Cannot read property 'errors' of undefined

      13 |
      14 |     get errorMessage() {
    > 15 |         for ( const propertyName in this.control.errors ) {
         |                                                  ^
      16 |             if (this.control.errors.hasOwnProperty(propertyName) && (this.control.dirty || this.control.touched)) {
      17 |                 return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      18 |             }

0 个答案:

没有答案