如何测试是否检查了html输入类型的单选

问题描述

我的component.html中有此HTML:

<input type="radio" [checked]="selected" (change)="select()" />

我该如何进行观众查询并期望测试是否已选中此输入元素?

我尝试过:

expect(spectator.query('input')).toHaveAttribute('checked');

但是我得到了错误

Error: Expected element to have attribute 'checked',but had 'undefined'

我已经尝试过:

expect(spectator.query('input')).toBeChecked();

但是我得到了错误

Error: Expected element to be checked

如何测试这个简单的HTML输入元素?

谢谢
索伦

解决方法

expect(spectator.query('input')).toBeChecked();是正确的用法。

由于未选中哪个单选按钮,selected属性似乎为false,您将收到此错误。在测试中通过简单地绑定您的绑定(通过将selected设置为true)或更新断言来检查是否未选中单选按钮:

expect(spectator.query("input[type=radio]")).not.toBeChecked();

看看this stackblitz代码示例,其中我有2个绑定的单选按钮,一个被选中,另一个未被选中,并且我对此进行了测试。

it("should be checked",() => {
  spectator = createComponent();
  expect(spectator.query("#r1[type=radio]")).not.toBeChecked();
});

it("should not be checked",() => {
  spectator = createComponent();
  expect(spectator.query("#r2[type=radio]")).toBeChecked();
});

另外,请查看this guide,以查看可用的自定义匹配器。