如何使用量角器测试元素是否具有类? [英] How to test if an element has class using Protractor?

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

问题描述

我正在尝试使用 Protractor 对 Angular 应用进行 e2e 测试,但还没有弄清楚如何检测元素是否具有特定的类.

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.

在我的例子中,测试点击提交按钮,现在我想知道 form[name="getoffer"] 是否有类 .ngDirty.可能的解决方案是什么?

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
    });
});

推荐答案

使用 toMatch() 时必须注意的一个问题是部分匹配.例如,假设您有一个元素可能具有 correctincorrect 类,并且您想测试它是否具有 correct 类.如果您使用 expect(element.getAttribute('class')).toMatch('correct'),即使元素具有 incorrect 类,它也会返回 true.

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.

我的建议:

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

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;
    });
};

您可以像这样使用它(利用 expect 自动解析 Protractor 中的承诺这一事实):

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天全站免登陆