TestCafe - 选择<select>中的选项

5
我有一个带有多个<option>标签的<select>。其中一些被使用类“is-disabled”禁用。我想要做的是选择列表中第一个可用的选项。为此,我使用了在testcafe网站上找到的示例(https://devexpress.github.io/testcafe/documentation/recipes/testing-select-elements.html),但似乎无法使其工作。

运行测试时,工具会单击选择并在第二次单击后关闭。之后,没有选定任何值。

有没有更好的方法来处理选项的动态选择?或者什么是更好的解决方案?任何帮助都将不胜感激!

问候 Cornel

SizeSelector component:

import {t, Selector} from 'testcafe';

class SizeSelector {

  constructor() {
    this._sizeSelector = Selector('.sizeSelectionGroup');
    this._selectors = this._sizeSelector.child('.productSizeSelection');
    this._widthSelector = this._selectors.nth(0);

    // todo other size types (single numeric/text)
  }

  // todo refactor
  async setFirstAvailableWidth() {
    const options = this._widthSelector.find('option'); // contains 13 elements while debugging
    const availableOptions = options.filter(node => {
      return !node.classList.contains('is-disabled');
    });

    const count = await availableOptions.count; // contains around 8 elements while debugging
    if (count > 0) {
      return await t
        .click(this._widthSelector)
        .click(availableOptions.nth(0))
        .expect(this._lengthSelector.value).ok(); // fails with value undefined
    }

    throw new Error('No available width found.');
  }
}

export default SizeSelector;

这可能是一个打字错误,但我没有看到_lengthSelector被定义。我确实看到你在构造函数中定义了_widthSelector。 - BarretV
2个回答

4
我不确定这个方案是否完全适用于你的情况。我试图模拟一个下拉菜单,其中有几个选项使用了类名'is-disabled',并使用一个函数进行测试,该函数将点击下拉菜单中第一个未被禁用的选项。我基于this编写了这个函数。 以下是我制作的示例下拉菜单:

https://jsfiddle.net/L6p2u/190/

这是测试代码(橙色应该是第一个没有禁用的选项)

import { Selector, t } from 'testcafe';

fixture `testcafe canvas`
    .page `https://jsfiddle.net/L6p2u/190/`;

const medwait            = 5000
const longwait           = 15000;
const dropdown           = Selector('#colour');

async function selectFirstAvailableOption(selector) {
    const select = selector;
    await t // select the first available option
        .setTestSpeed(0.7)
        .hover(select)
        .expect(select.hasAttribute("disabled")).notOk({timeout: 5000})
        .click(select)
        .click(select
            .find("option")
            .filter((node) => {
                if (node && node.className.indexOf('is-disabled') == -1) {
                    return true;
                }
                return false;
            })
            .nth(0)).wait(5000); // this wait is just so you can see
}

test('Instructor', async t => {
    await t
        .switchToIframe('[name="result"]')
    await selectFirstAvailableOption(dropdown);
});

1

通过这个解决方案,当您与下拉列表交互时,您可以避免调用".setNativeDialogHandler(() => true)"。

export async function create(name) {
  const dropdown = await Selector("#dropDownID");
  const dropdownOption = dropdown.find("option");

  await t
    .click(dropdown)
    .click(dropdownOption.withText(name))
    .click(Selector("#submitBtn"));
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接