我正在使用一个指令来获取用作过滤器文本的输入数据。
这是我在指令中的hostlistener:
@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});
}
这段代码工作正常,我无法对其进行单元测试。
我订阅了filterChanged EventEmitter,在我的单元测试中检查了值。
我尝试模拟按键事件来更改值,还尝试了设置值属性。这些都不适合我。
这是我的spec文件:
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);
}
}
任何人都可以帮助我,我怎样才能对它进行单元测试?
答案 0 :(得分:27)
我在单元测试中模拟按键时遇到了一些麻烦。但是Seyed Jalal Hosseini发现了一个答案。这可能就是你想要的。
如果您正在尝试模拟按键,则可以通过调用元素上的dispatchEvent(new Event('keypress'));
来触发事件。
以下是我所指的答案,其中提供了更多详细信息:https://stackoverflow.com/a/37956877/4081730
如果要设置按下的键,也可以这样做。
const event = new KeyboardEvent("keypress",{
"key": "Enter"
});
el.dispatchEvent(event);
我刚刚遇到的更多信息:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
答案 1 :(得分:3)
如果您想使用密钥代码(或“which”),您可以这样做:
int cols, rows;
int scl = 20;
void setup() {
size(400, 400);
int w = 400;
int h = 400;
cols = w / scl;
rows = h / scl;
}
void draw() {
background(255);
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
int xpos = x*scl;
int ypos = y*scl;
stroke(55);
if((mouseX >= xpos && mouseX <= xpos+scl) &&
(mouseY >= ypos && mouseY <= ypos+scl)){
fill(75);
if (mousePressed == true){
println("Clicked at: " + xpos + " and " + ypos);
fill(100);
//here is the desired location for the fill to remain constant even
//after unclicking and leaving hover
}
println("Mouse at: " + xpos + " and " + ypos);
}else{
fill(50);
}
rect(xpos, ypos, scl, scl);
}
}
}
答案 2 :(得分:0)
it('should trigger a TAB keypress event on an element', () => {
const tabKeypress = new KeyboardEvent('keypress', {
// @ts-ignore
keyCode: 9, // Tab Key
cancelable: true
});
const myTableEle = debugEle.nativeElement.querySelector('.your-element');
myTableEle.dispatchEvent(tabKeypress);
fixture.detectChanges();
});
// @ ts-ignore:-删除TS警告,因为不赞成使用keyCode。如果您想设置KeyboardEvent的“ key”属性,则不需要它。