Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StackOverflowGist_nightwatchjs-how-to-check-if-element-exists-without-creating-an-error-failure-exception
// Example adapted from the examples at http://nightwatchjs.org/guide#writing-tests
module.exports = {
'Navigate to google': function (browser) {
browser.windowMaximize();
browser.url('http://www.google.com');
browser.waitForElementVisible('body', 1000);
},
'Try a junk selector that doesnt exist, using .elements': function (browser) {
// Note that the status is 0
browser.elements('css selector', '#garbage-element-selector-xxxxxxxxxx', function (result) {
console.log('-----------------');
console.dir(result);
console.log('-----------------');
});
},
'Try a junk selector that doesnt exist': function (browser) {
// Note that the status is -1
browser.element('css selector', '#garbage-element-selector-xxxxxxxxxx', function (result) {
console.log('-----------------');
// Not printing the entire object, it's full of error text as expected
console.log(`status: ${result.status}`);
console.log('-----------------');
});
},
'Try a real selector': function (browser) {
// Now let's do something when the element does exists
// This replaces the line "browser.setValue('input[type=text]', 'nightwatch');"
// from the original example
browser.element('css selector', 'input[type=text]', function (result) {
console.log('-----------------');
console.dir(result);
console.log('-----------------');
if (result.status != -1) {
browser.setValue('input[type=text]', 'nightwatch');
} else {
console.log('->The element does not exist, we failed');
}
});
},
'Do the rest of the example test': function (browser) {
browser.waitForElementVisible('button[name=btnG]', 1000);
browser.click('button[name=btnG]');
browser.pause(1000);
browser.assert.containsText('#main', 'Night Watch');
browser.end();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment