如何使用 testcafe 打印承诺的内部文本?

how to print the inner text of a promise using testcafe?

我正在尝试做一个断言,打印出警告横幅的文本上下文。横幅仅在用户输入错误的登录信息时可见。这是断言:

await t
    .expect(login.alertMessage.exists)
    .notOk(
        "I don't see the user details page. I see this " +
        await login.alertMessage.innerText 

    );

如果他输入了错误的信息,断言总是会通过。

如果我做一个否定测试(意味着如果用户输入了正确的登录信息)断言将在这一行失败:await login.alertMessage.innerText 并且错误消息是

1) 无法获取有关节点的信息,因为指定的选择器与 DOM 树中的任何节点都不匹配。

如果我删除 await 中的 await login.alertMessage.innerText 那么断言不会向我显示横幅。相反,我看到

1) AssertionError:我没有看到用户详细信息页面。我看到这个:{"_then":[],"_taskPromise":null}:预期为假

如有任何帮助,我们将不胜感激。

您传递给 .notOk() 函数的参数表达式总是在 expect 语句完成断言之前执行。

这意味着await login.alertMessage.innerText总是在expect语句之前执行。

当用户输入正确的登录信息时,TestCafe 将找不到 alertMessage 选择器并输出您提到的第一个错误。

当您删除 await 关键字时,selector.innerTextPromise<string>;将此 Promise 与字符串连接将调用 Promise 上的 toString() 方法,但不会解析 Promise 本身。

你应该像这样重写你的 expect 语句:

const alertMessage = login.alertMessage;
if (await alertMessage.exists) {
    throw new Error(`user cannot login: ${await alertMessage.innerText}`);
}

但是这样做你可能会遇到另一个问题:警报弹出窗口需要一些时间才能出现在 DOM 中,并且可能会在 if 语句执行后出现,当用户使用时你会得到一个误报测试无法登录。

为防止这种情况,您必须在输入 if 语句之前实现自己的等待机制。 一种解决方案是:

const alertMessage = login.alertMessage;
await t.wait(5000);
if (await alertMessage.exists) {
    throw new Error(`user cannot login: ${await alertMessage.innerText}`);
}

您还可以使用更复杂的方法替换 await t.wait(5000),如 here

所述