我正在使用 jasmine karma 编写测试用例来测试自定义指令。 该指令用于文本类型的输入框,并防止输入字母。表单控件在这里由 Angular 注入(inject)。 Reference answer to add NgControl to access FormControl value
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
中开始这样做的,但我没有在您的规范文件中看到您同时编译了组件和指令。
我不认为在规范文件中需要重新定义组件
关于javascript - 在测试自定义指令时无法读取未定义的属性 'value',该指令使用 jasmine 在 Angular 中获取注入(inject)的表单控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63032919/