TestCafe - 如何在测试失败的情况下检查 Web 元素是否存在或不存在?

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

我正在尝试编写一个脚本,该脚本需要根据 CSS 选择器找到的特定浏览器对象是否存在来调整其工作流行为。

我不想使用 document.getElementByID 方法,因为这在技术上不是 CSS 选择器,而且我们整个企业都在 CSS 选择器上标准化,所以任何走 DOM 除了 CSS 选择器无论如何都无法通过我们的代码审查流程。

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

thingSelector 所在位置:

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

OpenThing 在哪里:

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

如果对象不存在并且我正在检查它是否存在,或者如果对象存在并且我正在检查它不存在,以及以下情况,我需要能够继续执行对象不存在,它不存在,对象不存在,我正在检查它不存在。

在所有情况下,我仍然需要继续工作流程。

逻辑硬币的两面我都试过了:

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

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

如果上述其中一个在一种情况下没有失败,那么在另一种情况下也会失败,而在第一个没有失败的情况下,另一个也会失败。我需要一些能给我逻辑的东西,但永远不会使脚本执行失败,并且仍然允许我 return True 或 False,具体取决于对象是否存在。

提前感谢您帮助我解决这个问题,也感谢您学习和提高我的 Javascript 技能!

您可以通过以下方式检查 if 条件中的异步 exists 属性:

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

您可以使用以下断言来测试存在和 non-existence 个元素:

test('Test existence and non-existence elements', async t => {
    await t
        .expect(Selector('#existing-element').exists)
        .expect(Selector('#non-existing-element').exists).notOk()
});

这个对我有用,你可以试一试

async veriryCreativeIconButtonNotExists(){
await t.expect(this.exportButton.exists).ok()
await t.expect(this.columnPickerIcon.exists).ok()
await t.expect(this.filterColumnIcon.exists).ok()
if (await t.expect(this.columnPickerIcon.exists).ok()){
  await t.expect(this.creavtiveIconButton.exists).ok()
  await t.click(this.creavtiveIconButton)
  await t.expect(this.creativeImage.exists).ok()
  await t.click(this.creativeImage)
} else {
  return false;
}
return true;
  • 如何检查一个元素是否存在:

      test('Element with id "element" exists', async t => {
      await t.expect(Selector('#element').exists).ok(); });
    
  • 如何检查元素是否不存在:

     test('Element with id "element" shouldn\'t exist', async t => {
     await t.expect(Selector('#element').exists).notOk(); });
    

查看官方documentation.