Protractor expectation that element is eventually present

烂漫一生 提交于 2019-12-04 10:58:25

Using the facts that

  • browser.wait returns a promise that is resolved once the condition function returns truthy, or rejected if it times out.

  • If expect is passed a promise, it only runs the expectation when the promise is resolved

You can make a function that wraps a call to browser.wait

function eventual(expectedCondition) {
  return browser.wait(expectedCondition, 2000).then(function() {
    return true;
  }, function() {
    return false;
  });
}

and then create an expectation

expect(eventual(protractor.ExpectedConditions.presenceOf(element(by.partialLinkText('Continue'))))).toBe(true);

Or, to make it work on any browser instance, you can monkey-patch the Protractor prototype

protractor.Protractor.prototype.eventual = function(expectedCondition) {
  return this.wait(expectedCondition, 2000).then(function() {
    return true;
  }, function() {
    return false;
  });
}

and can be used as

expect(browser.eventual(protractor.ExpectedConditions.presenceOf(element(by.partialLinkText('Continue'))))).toBe(true);

To avoid timeouts, you must make sure that the timeout passed to browser.wait is less than the the Jasmine async test timeout, which is specified as jasmineNodeOpts: {defaultTimeoutInterval: timeout_in_millis} in the protractor configuration file

The presenceOf expected condition used with a browser.wait() would allow to have a single line in the test:

var EC = protractor.ExpectedConditions;
browser.wait(EC.presenceOf(element(by.partialLinkText('Continue'))), 1000, 'Unable to find continue link');

where EC is protractor.ExpectedConditions - I usually make it global in onPrepare() through the global namespace.

Note that in case of a failure, you would have a Timeout Error, but with the Unable to find continue link error description.


As a side note, it is important to provide a meaningful custom error description, as you've already did. If you want to enforce it, there is a eslint-plugin-protractor plugin to ESLint static code analysis tool that would warn you if there is a browser.wait() used without an explicit error description text.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!