Javascript 使用量角器通过 className 定位按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28680576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Locating a button by className with Protractor
提问by r3x
I apologize if this is a newbie question, just starting out with web automation testing.
如果这是一个新手问题,我很抱歉,刚刚开始进行网络自动化测试。
I want to test a login screen page. Finding the name and password textfields was easy (just used by.model), however I am having issues locating the login button with my script.
我想测试一个登录屏幕页面。查找名称和密码文本字段很容易(仅使用by.model),但是我在使用脚本定位登录按钮时遇到问题。
I googled around and I should be able to find an element by className using element(by.css(.className)), however this fails to work and I am always getting NoSuchElementError: No element found using locator: By.cssSelector(".btn btn-lg btn-primary btn-block").
我四处搜索,我应该能够使用element(by.css(.className))通过 className 找到一个元素,但是这不起作用,我总是得到 NoSuchElementError: No element found using locator: By.cssSelector(".btn btn-lg btn-primary btn-block").
Any idea what I am doing wrong?
知道我做错了什么吗?
Thanks you in advance,
提前谢谢你,
LoginBtn HTML:
登录Btn HTML:
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-disabled="loading">login</button>
My code:
我的代码:
describe('Test login', function() {
var username = element(by.model('formData.email'));
var password = element(by.model('formData.password'));
var loginBtn = element(by.css('.btn btn-lg btn-primary btn-block'));
beforeEach(function() {
browser.get('some site'); //hidden on purpose
});
it('should have a title', function() {
username.sendKeys(1);
password.sendKeys(2);
loginBtn.click();
});
});
回答by alecxe
If you are checking for multiple classes, separate them with dots:
如果您要检查多个类,请用点分隔它们:
by.css('.btn.btn-lg.btn-primary.btn-block')
Though, I'd find the button by text - looks more reliable and readable:
不过,我会通过文本找到按钮 - 看起来更可靠和可读:
by.xpath('//button[. = "login"]')
Also, think about assigning the button an id(if this is under your control) attribute to ease the testing process:
此外,考虑为按钮分配一个id(如果这是在您的控制之下)属性以简化测试过程:
<button id="submitButton" class="btn btn-lg btn-primary btn-block" type="submit" ng-disabled="loading">login</button>
Then, it would be as easy as:
然后,它会很简单:
by.id('submitButton')
回答by Adnan Ghaffar
You can also use only one class to find the locator
您也可以只使用一个类来查找定位器
by.css('.btn-primary')
by.css('.btn-primary')
by class name
按班级名称
by.className('btn-primary')
by.className('btn-primary')

