Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

if(await things.thingSelector(thingName).exists) {
    // do something 
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...