I'm trying to test that a value has change on the form when i type on the input. The project is using Nrwl nx and the test tool is jest.
component :
export class InputNumericComponent implements OnInit, OnDestroy {
@Input() form: FormGroup;
@Input() controlName: string;
private _changeSubscription: Subscription;
private get _control(): AbstractControl | null {
return this.form?.get(this.controlName);
}
public ngOnInit(): void {
if (!this._control) {
return;
}
console.log('init called'); // ok
this._changeSubscription = this._control.valueChanges
.pipe(tap((newValue) => this._handleChange(newValue)))
.subscribe();
}
public ngOnDestroy(): void {
if (this._changeSubscription) {
this._changeSubscription.unsubscribe();
}
}
private _handleChange(value: string): void {
console.log('_handleChange'); // never called
}
public handleBlur(): void {
console.log('handleBlur'); // can be called by using dispatchEvent(new Event('blur'));
}
}
testing file :
describe('InputNumericComponent', () => {
let component: InputNumericComponent;
let fixture: ComponentFixture<InputNumericComponent>;
configureTestSuite(() => {
TestBed.configureTestingModule({
declarations: [InputNumericComponent],
schemas: [NO_ERRORS_SCHEMA],
});
});
beforeEach(() => {
fixture = TestBed.createComponent(InputNumericComponent);
component = fixture.componentInstance;
component.controlName = 'numeric';
component.form = new FormGroup({
numeric: new FormControl(),
});
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should update form', fakeAsync(() => {
component.ngOnInit();
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = '222';
// i tried both and others like keydown, keypress, etc..
input.nativeElement.dispatchEvent(new Event('change'));
input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
tick();
console.log('form', component.form.get('numeric')?.value); // null
expect(input.form.get('numeric')).toEqual('222');
}));
});
I don't know why but the input event doesn't trigger the valueChanges, if i dispatch a blur event the handleBlur function is called but i don't know how to trigger the valueChanges, i've tried keydown, keypress.
I've tried to dispatch an input event directly on the input and it works, the _handleChange is called but don't know why in the test it doesn't work.
I've tried the other method using fixture.nativeElement.querySelector('input') but it doesn't work too.
What am i doing wrong ?