Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestCafe - How to check if a web element exists or does not exist without failing the test?

Tags:

I'm trying to write a script that needs to adapt it's workflow behavior depending on whether a particular browser object found by CSS selector exists or does not exist.

I do not want to use a document.getElementByID method as this is not technically a CSS selector, and our entire enterprise is standardized on CSS selector so anything that walks the DOM other then a CSS selector won't make it past our code review process anyway.

var thing = await things.thingSelector(thingName); if (await t.expect(thing.exists).notOk()) {    await t.click(things.OpenThing(thingName)); } else {    return false; } return true; 

Where thingSelector is:

const thingSelector = name =>   Selector('p.thing-header-title span')     .withText(name)     .parent('div.thing'); 

Where OpenThing is:

const OpenThing = name =>     thingSelector(name)         .find('a.thing-footer-item')         .withText('Open'); 

I need to be able to continue execution if the object is not there and I'm checking that it exists, or if the object is there and I'm checking that it does not exist, and also the cases where the object is not there and it does not exist and the object is not there and I'm checking that it does not exist.

In all cases I still need to proceed with the workflow.

I've tried both sides of the logic coin:

if (!await t.expect(thing.exists).ok()) 

And

if (await t.expect(thing.exists).notOk()) 

If one of the above doesn't fail in one scenario it will fail in the other, and the other one will fail in the scenario that the first one didn't fail. I need something that will give me the logic, but not ever fail the script execution and still allow me to return either True or False depending on if the object is present or not present.

Thank you in advance for helping me to solve this problem, and also to learn and grow in my Javascript skills!

like image 566
Seth Eden Avatar asked Nov 17 '17 21:11

Seth Eden


2 Answers

You can check the async exists property in the if condition in the following way:

if(await things.thingSelector(thingName).exists) {     // do something  }  
like image 114
Alexander Moskovkin Avatar answered Sep 21 '22 16:09

Alexander Moskovkin


You can use the following assertions to test existence and non-existence elements:

test('Test existence and non-existence elements', async t => {     await t         .expect(Selector('#existing-element').exists)         .expect(Selector('#non-existing-element').exists).notOk() }); 
like image 42
Mauricio Sánchez Avatar answered Sep 22 '22 16:09

Mauricio Sánchez