提问人:Parth Gondaliya 提问时间:11/3/2023 最后编辑:James ZParth Gondaliya 更新时间:11/3/2023 访问量:33
关于多个 mat-select 和 mat-option 的测试用例
Test case about multiple mat-select and mat-option
问:
it('should update control2 options when control1 is changed to "b"', (() => {
const control1Select = fixture.nativeElement.querySelector(
'mat-select[formControlName="control1"]'
);
const control2Select = fixture.nativeElement.querySelector(
'mat-select[formControlName="control2"]'
);
// Select "b" for control1
control1Select.value = 'b';
control1Select.dispatchEvent(new Event('change'));
fixture.detectChanges();
const control2Options = control2Select.querySelectorAll('mat-option');
expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
}));
我尝试了很多解决方案,但没有成功。当用户从 Control1 中选择一个选项时,Control2 的选项将使用文件中.ts函数来决定。需要为此功能编写测试用例。
我还添加了 fakeAsync 和 tick。
我也试过:
control1Select.value = 'b';
control1Select.dispatchEvent(new Event('change'));
我也试过:
fixture.whenStable().then(() => {
const control2Options = control2Select.querySelectorAll('mat-option');
expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
done();
});
错误:预期 0 为 3。
答:
0赞
AliF50
11/3/2023
#1
这就是为什么在这些情况下,使用反应式表单API可能更可取,因为可能很难使JavaScript事件和HTML正确更改值。
像这样的事情很难看到更新:
control1Select.value = 'b';
control1Select.dispatchEvent(new Event('change'));
fixture.detectChanges();
如果我是你,我会直接从 TypeScript 更改表单控件。
it('should update control2 options when control1 is changed to "b"', () => {
// Select "b" for control1, use setValue
component.form.get("control1").setValue("b");
fixture.detectChanges();
const control2Select = fixture.nativeElement.querySelector(
'mat-select[formControlName="control2"]'
);
const control2Options = control2Select.querySelectorAll('mat-option');
expect(control2Options.length).toBe(3); // Expect 3 options when control1 is "b"
});
评论
0赞
Parth Gondaliya
11/4/2023
有没有其他方法不使用 TypeScript ?
评论