关于多个 mat-select 和 mat-option 的测试用例

问题描述 投票:0回答:1
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 选择一个选项时,将使用 .ts 文件中的函数决定 control2 的选项。需要为此功能编写测试用例。

我还添加了 fakeAsync 和勾选。

我也尝试过:

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。

angular testing jasmine karma-jasmine
1个回答
0
投票

这就是为什么在这些场景中,使用反应式表单 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"
});
© www.soinside.com 2019 - 2024. All rights reserved.