I am writing test cases using jasmine karma to test a custom directive. The directive is used on an input box of type text and prevents alphabets from being entered. The form control is injected by Angular here. 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);
}
}
I am new to Angular and after reading articles on how to test a custom directive, I read about creating a test component.
I tried the following. But the test case does not cover the above input method and mostly form control value is not set.
Please help.
Here the code of my testing component and spec file
@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]],
});
}
}
Spec file
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'));
});
Here this is the test case
it('for keypress input', () => {
inputElement.triggerEventHandler('input', {});
fixture.detectChanges();
// did not expect anything for now. Just checking code is covered or not
});
Update: Here is the error while running the ng test
ERROR: 'ERROR', TypeError: Cannot read property 'value' of undefined
TypeError: Cannot read property 'value' of undefined
at Object.eval [as handleEvent]
TypeError: Cannot read property 'value' of undefinedbut ratherSPEC HAS NO EXPECTATIONS for keypress input- yurzui