2017-06-21 298 views
0

我想用輸入測試簡單的角度分量。測試:模擬模擬

所以在底部的一個例子幾乎沒有準備測試,並在一個組件應該發生test功能模糊,它顯示日誌,但我沒有控制檯中的日誌。我嘗試了2種情況:獲取div native元素並單擊它並使用blur()函數輸入本地元素。在角度應用模糊成功發生,但它在測試中不起作用。我該如何解決它?

@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(); 
    })) 
} 

回答

0

使用

dispatchFakeEvent(inp, 'blur'); 

這裏是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)); 
}