使用Angular | Event Listeners进行因果报应单元测试



考虑这部分代码:

@ViewChild('amountSlider') amountSlider: any;
@ViewChild('amountInput') amountInput: any;
** Some Code **
setvariables()
{
const updateStep =  this.renderer.listen(this.amountInput.input.nativeElement, 'keydown', (evt) => {
this.amountSlider.step = 1;
const keyName = evt.key;
if (keyName == 'Tab') {
this.amountSlider.step = 100;
}
});
const resetStep = this.renderer.listen(this.amountSlider.slider.nativeElement, 'mouseover', (evt) => {
this.amountSlider.step = 100;
});
}

下面的部分(事件侦听器(我的代码在单元测试中困扰着我我不是直接从DOM调用keydown或mouseover。有人能帮我写单元测试吗???

test.spec.ts

describe('setVariables', () => {
it('makes expected calls', () => {
const renderer2Stub: Renderer2 = fixture.debugElement.injector.get(Renderer2);
spyOn(renderer2Stub, 'listen');
comp.setVariables();
expect(renderer2Stub.listen).toHaveBeenCalled();
}) 
});

使用键代码的KeyboardEvent尝试此操作

describe('setVariables', () => {
it('makes expected calls', () => {
const renderer2Stub: Renderer2 = fixture.debugElement.injector.get(Renderer2);
spyOn(renderer2Stub, 'listen');
// for down arrow event for example 
comp.setVariables();
const event: Event = new KeyboardEvent('keydown', {
'code': '40' 
});
window.dispatchEvent(event);
fixture.detectChanges();
expect(renderer2Stub.listen).toHaveBeenCalled();
}) 
});

相关内容

  • 没有找到相关文章

最新更新