本文介绍了如何测试 img 标签是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我做 expect(img).not.toBe(null) 然后我得到一个错误:错误:期望使用 WebElement 参数调用,期望 Promise.您的意思是使用 .getText() 吗?.我不想在 img 中获取文本,我只想知道页面上是否存在标签.

if I do expect(img).not.toBe(null) then I get an error:Error: expect called with WebElement argment, expected a Promise. Did you mean to use .getText()?. I don't want to get the text inside an img, I just want to know if the tag exists on the page.

describe('company homepage', function() {
it('should have a captcha', function() {

    var driver = browser.driver;
    driver.get('http://dev.company.com/');

    var img =driver.findElement(by.id('recaptcha_image'));

    expect(img.getText()).not.toBe(null);
});
});

通过了,但我不确定它是否在测试正确的东西.将 id 更改为不存在的内容确实会失败.

Passes but I'm not sure it is testing the right thing. Changing the id to something that doesn't exist does fail.

如何在非角度应用上下文中使用量角器正确测试标签是否存在?

How do I properly test for a tag to exist with protractor in a non-angular app context?

推荐答案

Edit 2:

根据下面的 Coding Smackdown,量角器现在提供了更短的答案:

Per Coding Smackdown below, an even shorter answer is now available in protractor:

expect(element(by.id('recaptcha_image')).isPresent()).toBe(true);

编辑 1:

我今天发现了 isElementPresent(),对于我在下面描述的内容,它只是一个更具可读性的快捷方式.请参阅:http://www.protractortest.org/#/api

I discovered isElementPresent() today which is just a more readable shortcut for what I described below. See: http://www.protractortest.org/#/api

您的用法是:

driver.isElementPresent(by.id('recaptcha_image')).then(function(present){
    expect(present).toBe(false);
})

旧答案(这可行,但以上对读者更友好)


Old answer (this works but the above is more reader friendly)

通常,如果您不确定标签是否存在,您应该使用 findElements(或 $$,它是 css 中 findElements 的别名).然后测试数组长度.FindElement(和 $)如果找不到元素只会抛出错误.

In general you should use findElements (or $$ which is an alias for findElements by css) if you're not sure a tag will be there. Then test for the array length. FindElement (and $) will just throw an error if it cant find the element.

因此代替

var img =driver.findElement(by.id('recaptcha_image'));

expect(img.getText()).not.toBe(null);

使用:

driver.findElements(by.id('recaptcha_image')).then(function(array){
    expect(array.length).not.toBe(0);
})

此外,getText() 返回一个 promise,这就是您收到该错误的原因.

Also, getText() returns a promise which is why you're getting that error.

这篇关于如何测试 img 标签是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 11:21