首页 > 解决方案 > 在测试使用 jasmine 在 Angular 中获取注入表单控件的自定义指令时无法读取未定义的属性“值”

问题描述

我正在使用 jasmine karma 编写测试用例来测试自定义指令。该指令用于文本类型的输入框并防止输入字母。表单控件在这里由 Angular 注入。 添加 NgControl 以访问 FormControl 值的参考答案

export class PreventAlphaDirective {
    public regex = //get some regex values from a const file
    
    constructor(public formControl: NgControl) {} //injected by Angular. Having difficulty here to pass form control value from jasmine I GUESS

    @HostListener('input', ['$event'])
    input(event: KeyboardEvent) {
        const val = this.formControl.control.value;
        let inp = '';
        for (const char of val) {
           if (char.match(this.regex.NUMBERS)) {
             inp += char;
           }
        }
      this.formControl.control.setValue(inp);
    }
}

我是 Angular 的新手,在阅读了有关如何测试自定义指令的文章后,我阅读了有关创建测试组件的信息。

我尝试了以下。但测试用例并未涵盖上述输入法,而且大多没有设置表单控件值。

请帮忙。

这是我的测试组件和规范文件的代码

@Component({
selector: 'app-testingcomponent',
template:
    `<form [formGroup]="testForm">     
     <input type="text" formControlName="amount" appPreventAlpha />
    </form> `,
    styleUrls: ['./testingcomponent.component.scss'],
    })
export class TestingcomponentComponent implements OnInit {
       constructor(private fb: FormBuilder) { }
       public testForm: FormGroup;
       ngOnInit() {
           this.testForm = this.fb.group({
           amount: ['12345', [Validators.required]],
           });
       }
    } 

规格文件

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

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [ReactiveFormsModule, FormsModule],
        declarations: [TestingcomponentComponent, PreventAlphaDirective],
    });
})); 

beforeEach(() => {
  fixture = TestBed.createComponent(TestingcomponentComponent);
  fixture.detectChanges();
  component = fixture.componentInstance;
  inputElement = fixture.debugElement.query(By.css('input'));
}); 

这是测试用例

it('for keypress input', () => {
     inputElement.triggerEventHandler('input', {});
     fixture.detectChanges();
     // did not expect anything for now. Just checking code is covered or not
}); 

更新:这是运行 ng 测试时的错误

ERROR: 'ERROR', TypeError: Cannot read property 'value' of undefined
TypeError: Cannot read property 'value' of undefined
at Object.eval [as handleEvent] 

标签: javascriptangularjasmine

解决方案


我认为更直接的方法是使用控件属性为其创建一个测试组件,并在组件模板中使用您的指令。你实际上开始这样做了,app-testingcomponent但我没有在你的规范文件中看到你编译了你的组件和指令。

我认为规范文件中不需要重新定义组件


推荐阅读