单击基于文本的按钮

Clicking a button based on the text

我正在使用 TestCafe 测试本地 运行 应用程序,除以下问题外没有问题:

我有一个如下所示的元素:

<a href="internallink" class="btn btn-success">Upload file</a>

当测试尝试使用

单击元素时
.click(Selector('.btn').withText('Upload file'))

报如下错误

   1) The specified selector does not match any element in the DOM tree.

         | Selector('.btn')
       > |   .withText('Upload new file')

如能提供任何可能出错的提示,我们将不胜感激。

我检查了 Bootstrap 网站上的一个按钮,点击它有一个类似的按钮,它按预期工作。请看下面的代码:

import { Selector } from 'testcafe';

fixture `bootstrap`
.page `https://getbootstrap.com/docs/4.2/components/buttons/`;

test(`click button`, async t => {
    await t.click(Selector('.btn').withText('Success'));
});

我建议您检查您的网站并确保:

  1. 按钮的 offsetWidthoffsetHeight 大于零。
  2. 该按钮没有 display:nonevisibility: hidden 等样式。
  3. 该按钮包含与您正在搜索的完全相同的文本。

    如果这没有帮助,如果您分享您的项目或网站 url 来演示该问题,那就太好了。

当 TestCafe 给出此错误消息时:The specified selector does not match any element in the DOM tree,而我不知道发生了什么,我采取了以下路径:

我创建了一个以元素为目标的 Selector 变量,并在单击它之前将鼠标悬停在它上面:

const uploadFileButton = Selector('a.btn').withExactText('Upload file');
await t
    .hover(uploadFileButton)
    .click(uploadFileButton);

请注意,在上面的代码中,我在定义选择器时尽量做到具体。

如果在 运行 时,您没有看到 TestCafe 光标移向目标元素(这意味着您没有 运行 在无头模式下),那么您知道选择器是错的。这可能是因为在 TestCafe 尝试将鼠标悬停在它上面时,该元素尚未安装在 DOM 中。为了验证这一点,将 TestCafe 代码修改为:

const uploadFileButton = Selector('a.btn').withExactText('Upload file');
await t
    .expect(uploadFileButton.exists)
    .ok({timeout: 10000})
    .hover(uploadFileButton)
    .click(uploadFileButton);

如果在 运行 时,TestCafe 在 .ok() 行停止,那么您就知道选择器肯定是错误的。 在这种情况下,转到开发人员工具并在控制台中键入以下命令:

var el = document.querySelectorAll('a.btn');
el <ENTER>

检查 el 元素的内容。如果您找到目标按钮,那么您应该检查 innerText 属性 并且您应该检查是否没有 CSS 规则使文本变为大写或使其不可见。