如何在不等待检查选择器是否不存在 Node.js 和 TestCafe 的情况下编写 if 条件

How to write an if condition without waiting for checking if a selector does NOT exist with Node.js and TestCafe

抱歉,总的 N00b 问题,但是,

我正在编写一些测试自动化,我正在自动化的网站有时在页面上的某些元素上有某些行为,而在其他时候它在页面上的不同元素上有不同的行为。它通常属于两种模式之一。称之为模式A和模式B。 问题是模式 A 和模式 B 之间有一些共享元素,所以它不是完全不同的元素。

但是,无论哪种情况,当模式 B 处于活动状态时,屏幕上始终有一个元素,而当模式 A 处于活动状态时,它不在屏幕上。 此外,模式 A 的工作流程略长,带有一些额外的交互控件。让我们称这个元素为 "ProfileIdentifier"。我有一个定位器,我想编写一些逻辑代码来检查这个元素是否不存在,然后与额外的控件交互并执行更长的工作流程,然后是公共控件和工作流程之间常见的模式A & 模式B.

简而言之,是这样的:

import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.

async function FillOutForm(t) {
    var profileIdentifier = t.getElement(mypage.profileIdentifierLocator);
    if (not(profileIdentifier.exists)) {
        // Do the extra workflow
    }
    // Do the common workflow
}

或者可能是这样的:

import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.

async function FillOutForm(t) {
    var profileIdentifier = t.getElement(mypage.profileIdentifierLocator);
    if (profileIdentifier.exists.notOk()) {
        // Do the extra workflow
    }
    // Do the common workflow
}

注意:我看过其他类似的问题,例如: related question #1

我确实从这个问题的其中一个答案中看到了一线希望:

$('.myModal').isPresent().then(function(inDom) {
     return inDom; // returns bool
};

我正在使用 Atom JavaScript 编辑器,结合 TestCafe 和 ES6,我更愿意远离像 getElementById 这样的代码,因为这不是最好的(性能和稳定的)方式在 JavaScript 中利用 CSS 定位器,尤其是当我们必须在网站的其他部分重复使用类似定位器来进行样式设置和其他测试自动化时。

您可以使用 exists 异步 属性 检查元素是否存在。

import mypage from '../../page-objects/mypage'; //JS file with all the locators for that page.

async function FillOutForm(t) {
    if (!await mypage.profileIdentifierLocator.exists) {
        // Do the extra workflow
    }

    // Do the common workflow
}