如何使用量角器测试元素是否具有类?

编程入门 行业动态 更新时间:2024-10-27 08:30:18
本文介绍了如何使用量角器测试元素是否具有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 00:50:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1012513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:量角器   如何使用   元素   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!