问题
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();
}))
}
回答1:
You can use dispatchEvent
to emulate a blur:
inp.dispatchEvent(new Event('blur'));
回答2:
Use
dispatchFakeEvent(inp, 'blur');
and here is dispatchFakeEvent:
export function createFakeEvent(type: string) {
const event = document.createEvent('Event');
event.initEvent(type, true, true);
return event;
}
export function dispatchFakeEvent(node: Node | Window, type: string)
{
node.dispatchEvent(createFakeEvent(type));
}
来源:https://stackoverflow.com/questions/44681595/testing-blur-emulate