无法在Angular 2单元测试(Jasmine)中模拟按键事件
我正在使用一个指令来获取用作过滤器文本的输入数据。
I am using a directive to get the data from input used as a filter text.
这是我在指令中的hostlistener:
here is my hostlistener in the directive:
@HostListener('input', ['$event.target.value'])
public onChangeFilter(event: any): void {
console.log('input event fired, value: ' + event);
this.columnFiltering.filterString = event;
this.filterChanged.emit({filtering: this.columnFiltering});
}
此代码工作正常,我无法对其进行单元测试。
this code is working perfectly, I am unable to unit test the same.
我已经订阅了filterChanged EventEmitter,在我的单元测试中检查了值。
I have subscribed to the filterChanged EventEmitter, in my unit test to check the value.
我尝试模拟按键事件来更改值并尝试设置值属性。这些都不适合我。
I tried simulating keypress event to change value and also tried settings value attribute. None of these is working for me.
这是我的spec文件:
here is my spec file:
describe('Table View', () => {
let fixture: ComponentFixture<any>;
let context: TableComponent;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
TableComponent,
],
imports: [TableModule],
});
fixture = TestBed.createComponent(TableComponent);
context = fixture.componentInstance;
});
it('should allow filter', () => {
const element = fixture.nativeElement;
context.config = config;
fixture.detectChanges();
let tableChangeCount = 0;
let tableEvent: any;
context.tableChanged.subscribe((event: any) => {
tableChangeCount++;
tableEvent = event;
});
// Check if table exists
let inputElement = element.querySelectorAll('tr')[1].querySelector('input');
let e = new KeyboardEvent("keypress", {
key: "a",
bubbles: true,
cancelable: true,
});
inputElement.dispatchEvent(e);
});
});
我尝试设定价值:
let attrs = inputElement.attributes;
inputElement.setAttribute('value', 'abc');
for (let i = attrs.length - 1; i >= 0; i--) {
// Attribute value is set correctly
if (attrs[i].name === 'value') {
console.log(attrs[i].name + "->" + attrs[i].value);
}
}
任何人都可以帮助我,我该如何进行单元测试同样的?
Can anyone please help me, how can I unit test the same?
我在单元测试中模拟按键时遇到了一些麻烦。但是Seyed Jalal Hosseini发现了一个答案。它可能就是您所追求的。
I've had some trouble simulating a keypress in a unit test also. But came across an answer by Seyed Jalal Hosseini. It might be what you're after.
如果您正在尝试模拟按键,则可以通过调用 dispatchEvent(新事件)来触发事件('keypress'));
关于元素。
If you're attempting to simulate a keypress you can trigger an event by calling dispatchEvent(new Event('keypress'));
on the element.
这是我所指的答案,它提供了更多细节: https://stackoverflow.com/a/37956877/4081730
Here is the answer I'm referring to which gives more detail : https://stackoverflow.com/a/37956877/4081730
如果你想设置按下的键,也可以这样做。
If you want to set the key that was pressed, this can be done also.
const event = new KeyboardEvent("keypress",{
"key": "Enter"
});
el.dispatchEvent(event);
我刚刚遇到的更多信息: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Further information I've just come across: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events