无法判断按钮启用/禁用状态:断言'true'为true失败求助
问题:检查按钮disabled属性时测试断言失败,原因是什么?
我在写UI自动化测试时,尝试定位按钮并验证它是否带有disabled属性,写了这段代码:
expect(audiencePage.saveAudienceBtn.getAttribute('disabled')).toBe(true);
但运行测试后抛出了异常:
-Expected 'true' to be true. Executed 7 of 7 specs (1 FAILED) in 18 secs. [13:44:18] I/launcher - 0 instance(s) of WebDriver still running [13:44:18] I/launcher - chrome #01 failed 1 test(s) [13:44:18] I/launcher - overall: 1 failed spec(s) [13:44:18] E/launcher - Process exited with error code 1
想请教下这个错误的根源是什么?
原因分析与修复方案
这个问题其实很常见,核心是数据类型不匹配导致的:
- WebDriver的
getAttribute('disabled')方法返回的是字符串类型的'true',而你用toBe(true)断言的是布尔类型的true。JavaScript里字符串和布尔值是严格不同的,所以断言直接失败了。 - 补充个小细节:如果按钮没有设置
disabled属性,getAttribute('disabled')会返回null,而不是你可能以为的false;只有当按钮明确添加了disabled属性(不管是写disabled="disabled"还是HTML5的简写disabled),这个方法才会返回字符串'true'。
修复方法
你可以选下面两种方式中的任意一种来修正断言:
- 匹配字符串类型的返回值:
expect(audiencePage.saveAudienceBtn.getAttribute('disabled')).toBe('true');
- 使用更贴合场景的断言方法:
很多UI测试框架(比如Protractor)都提供了专门检查元素启用/禁用状态的方法,比如isEnabled(),它会直接返回布尔值,用起来更直观:
// 元素禁用时isEnabled()返回false,所以断言为false expect(audiencePage.saveAudienceBtn.isEnabled()).toBe(false);
这种方式也能避免类型匹配的坑,推荐优先使用。
内容的提问来源于stack exchange,提问作者James Delaney
相关产品推荐
相关产品推荐

