gpt4 book ai didi

javascript - 如何模拟事件并将其传递给 Jasmine 测试中的方法?

转载 作者:行者123 更新时间:2023-12-05 05:13:31 24 4
gpt4 key购买 nike

我是 Jasmine 测试的新手,我正在尝试为更改事件编写单元测试,这需要事件作为方法参数中的模拟值,但我无法实现它。这是我试过的

    it('sample test', () => {
const compiled = fixture1.debugElement;
const event = {
preventDefault: jasmine.createSpy(),
srcElement: jasmine.createSpy()
};
spyOn(component1, 'onChange');
const select = compiled.query(By.css('#elect-menu')).nativeElement;
select.value = select.options[1].value;
select.dispatchEvent(new Event('change'));
fixture1.detectChanges();
expect(component1.onChange).toHaveBeenCalled();`

我的 html 代码是这样的

<select id="select-menu" (change)="onChange($event)" (dblclick)="onChange($event)"> 
<option value="default">some value</option>
<option *ngFor="let line of lines" [value]="line.id" >{{line.name}}</option>
</select>

我的组件方法将在更改时调用 onChange($事件) {

const selected = parseInt($event.target.value);
switch (selected) {
case 1: {
//some logic
break;
}
}

我想写一个测试用例来测试案例1中的正流和负流。

最佳答案

这里发生了一些事情。首先,没有必要对您正在测试的组件内部的方法使用 spyOn。相反,您应该使用 expect() 来检查 onChange() 方法是否执行了预期的操作。例如:

onChange($event) {
const selected = parseInt($event.target.value);
switch (selected) {
case 1:
this.testValue = 1; // Set some variable based on the selected value
break;
...
}
}

it('sample test', () => {
const compiled = fixture1.debugElement;
const select = compiled.query(By.css('#select-menu')).nativeElement;
select.value = select.options[1].value;
select.dispatchEvent(new Event('change'));
fixture1.detectChanges();

expect(component.testValue).toBe(1); // Check to see if the variable is correctly set
}

其次,你这里有一个错字:const select = compiled.query(By.css('#elect-menu')).nativeElement; - 应该是 '#select-菜单';

如果你真的只是想在你的方法上使用 spy ,正确的语法是:

let methodSpy = spyOn(component1, 'onChange').and.callThrough();
// Do something that triggers the method
expect(methodSpy).toHaveBeenCalled();

关于javascript - 如何模拟事件并将其传递给 Jasmine 测试中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53582384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com