考虑这部分代码:
@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();
})
});
答案 0 :(得分:2)
使用带有键盘代码的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();
})
});