我遇到了有关 jquery 的问题。 我正在尝试测试两条路径:
it("should return true when country is valid", function() {
var validCountry = "Germany";
$("#fld_country option:selected").val(validCountry);
expect(isValid("#fld_country")).toBeTruthy();
});
it("should return false when country is invalid", function() {
var invalidCountry = "";
$("#fld_country option:selected").val(invalidCountry);
expect(isValid("#fld_country")).toBeFalsy();
});
validCountry
和 invalidCountry
是从下拉列表中选择的选项。
这是 isValid 函数:
function isValid(selector) {
if (selector === "#fld_country option:selected") {
return validator.isSelectedField(selector);
}
else return validator.isFieldEmpty(selector);
}
这是isSelectedField
:
isSelectedField: function (selector) {
return $.trim($('selector option:selected').html())
问题是它失败的原因是:
validate registration form should return true when country is valid
和
validate registration form should return false when country is invalid FAILED
我不知道问题是什么......有什么想法吗?
最佳答案
您的isValid
函数将始终返回 validator.isFieldEmpty(selector)
自 selector
值不匹配 - 您比较 #fld_country
至#fld_country option:selected
。
也许这就是问题所在。
//编辑
好的。确保您设置了正确的模板。您提到您使用 jasmine-jquery 固定装置。在测试运行之前,您可以检查选择是否有任何选项。
我相信您正在尝试通过 jquery 设置所选选项 - 这有一个错误,应该是:
$("#fld_country").val(validCountry);
如果您的 <select>
这将起作用看起来像这样(所以再次检查你的模板)
<select id="fld_country">
<option value="Poland">Poland</option>
<option value="Germany">Germany</option>
</select>
您遇到的另一个问题位于 isSelectedField
功能。而不是
return $.trim($('selector option:selected').html())
你可能想要这样的东西:
return $.trim($(selector + ' option:selected').html())
因为你想使用selector
变量不是字符串。
关于javascript - 使用 jQuery 从下拉列表中获取选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257943/