javascript - 在测试使用 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]
解决方案
我认为更直接的方法是使用控件属性为其创建一个测试组件,并在组件模板中使用您的指令。你实际上开始这样做了,app-testingcomponent
但我没有在你的规范文件中看到你编译了你的组件和指令。
我认为规范文件中不需要重新定义组件
推荐阅读
- python - 如何增加 csv 文件的默认列宽,以便在打开文件时所有文本都正确适合?
- r - lm函数翻转交互项的顺序
- c++ - 如何区分 llvm IR 代码中的堆栈/堆地址?
- jquery - 淡出容器,改变内容,淡入容器
- c - 通过插入新元素的链表c编程错误
- avro - org.apache.avro.SchemaParseException:“枚举”不是定义的名称
- jquery - 为什么没有按预期添加和删除我的课程?
- java - la4j 主要特征值 - 在 java 8 中将命令式算法转换为函数式风格
- c++ - 错误:“fuse_operations_compat2”没有名为“readdir”的非静态数据成员
- javascript - 在一个图中为多个图形自定义工具提示