如何测试一个元素是否用量角器有课吗? [英] How to test if an element has class using Protractor?

查看:144
本文介绍了如何测试一个元素是否用量角器有课吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出来量角器端到端测试角应用程序,还没有想出如何检测,如果一个元素有一个特定的类或没有。

在我的情况下,在测试点击提交按钮,现在我想知道,如果形式[NAME =getoffer]有类.ngDirty。可能是什么办法呢?

 描述('联系表格',函数(){
    beforeEach(函数(){
        browser.get(的http://本地主机:9000');
        。元素(by.linkText('与我联系'))点击();
    });    它('失败了表单验证,各个领域的原始',函数(){
        元素(by.css('形式[NAME =getoffer]输入[类型=提交]'))点击()。
        期待(元素(by.name('getoffer')))toHaveClass('ngDirty')。 //< - 这条线
    });
});


解决方案

有一个问题,你必须寻找出使用 toMatch(),作为公认的答案,是部分匹配。举例来说,假设你有可能具有类的元素正确不正确,和你想测试它具有类正确。如果你使用预期(element.getAttribute(类))。toMatch('正确'),这将返回true,即使元素具有不正确类。

我的建议是:

如果您希望只接受完全匹配,你可以为它创建一个辅助方法:

  VAR hasClass =功能(元素,CLS){
    返回element.getAttribute(类)。然后(函数(类){
        返回classes.split('').indexOf(CLS)== -1!;
    });
};

您可以使用它像这样(的事实,即期望自动解析承诺在量角器趁着):

 预期(hasClass(元素(by.name('getoffer')),'ngDirty'))TOBE(真)。

I'm trying out Protractor to e2e test Angular app and haven't figured out how to detect if an element has a specific class or not.

In my case, the test clicks on submit button and now I want to know if form[name="getoffer"] has class .ngDirty. What may be the solutions?

describe('Contact form', function() {
    beforeEach(function(){
        browser.get('http://localhost:9000');
        element(by.linkText('Contact me')).click();
    });

    it('should fail form validation, all fields pristine', function() {
        element(by.css('.form[name="getoffer"] input[type="submit"]')).click();
        expect(element(by.name('getoffer'))).toHaveClass('ngDirty'); // <-- This line
    });
});

解决方案

One gotcha you have to look out for with using toMatch(), as in the accepted answer, is partial matches. For instance, let's say you have an element that might have the classes correct and incorrect, and you want to test that it has the class correct. If you were to use expect(element.getAttribute('class')).toMatch('correct'), that will return true even if the element has the incorrect class.

My suggestion:

If you want to only accept exact matches, you can create a helper method for it:

var hasClass = function (element, cls) {
    return element.getAttribute('class').then(function (classes) {
        return classes.split(' ').indexOf(cls) !== -1;
    });
};

You can use it like this (taking advantage of the fact that expect automatically resolves promises in Protractor):

expect(hasClass(element(by.name('getoffer')), 'ngDirty')).toBe(true);

这篇关于如何测试一个元素是否用量角器有课吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆