I would like to test simple angular component with input.
So an example in the bottom has little preparation for the test, and in a component should occur test
function on blur, which shows log, but I have no logs in console. I tried 2 cases: getting div native element and click it and use blur()
function for input native element. In angular app blur successfully occur, but it doesn't work in test. How can I fix it?
@Component({
template: '<div><input [(ngModel)]="str" (blur)="testFunc($event)" /></div>'
})
class TestHostComponent {
it: string = '';
testFunc = () => {
console.log('blur!!!');
}
}
describe('blur test', () => {
let component: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let de: DebugElement;
let inputEl: DebugElement;
beforeEach(() => { /* component configuration, imports... */ }
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
inputEl = fixture.debugElement.query(By.css('input'));
fixture.detectChanges();
})
it('test', async(() => {
const inp = inputEl.nativeElement;
inp.value = 123;
inp.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.it).toEqual('123');
inp.blur();
const divEl = fixture.debugElement.query(By.css('div'));
divEl.nativeElement.click();
}))
}
You can use dispatchEvent
to emulate a blur:
inp.dispatchEvent(new Event('blur'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With