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

爷,独闯天下 提交于 2019-11-28 02:50:45

问题


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!


回答1:


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

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



回答2:


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()
});


来源:https://stackoverflow.com/questions/47359687/testcafe-how-to-check-if-a-web-element-exists-or-does-not-exist-without-failin

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