5

在我的测试中,我想模拟“cancelUpgrade”按钮中的点击,只有当它显示时:

it('should be in home menu', async () => {
  await waitFor(element(by.id('cancelUpgrade')))
    .toBeVisible()
    .withTimeout(2000);
  await element(by.id('cancelUpgrade')).tap();
});

它返回预期的错误Error: Cannot find UI element.

https://github.com/wix/detox

4

3 回答 3

7

您可以将 tap 包装在 try/catch 块中:

it('should be in home menu', async () => {
  await waitFor(element(by.id('cancelUpgrade')))
    .toBeVisible()
    .withTimeout(2000);
  try {
    await element(by.id('cancelUpgrade')).tap();
  } catch (e) {}
  // continue your tests
});

不是最好的方法,但我认为这是目前在排毒中可能的方法。

于 2017-10-04T14:06:57.097 回答
0

我怀疑我们可以使用这种模式toExist

it('should be in home menu', async () => {
  await waitFor(element(by.id('cancelUpgrade')))
    .toBeVisible()
    .withTimeout(2000);
  try {
    await expect(element(by.id('cancelUpgrade'))).toExist();
  } catch (e) {}
  // continue your tests
});

如果您不需要等待:

it('should be in home menu', async () => {
  try {
    await expect(element(by.id('cancelUpgrade'))).toExist();
  } catch (e) {}
  // continue your tests
});
于 2018-10-02T17:19:24.410 回答
0

它可能不是最好的解决方案,但我创建了一个名为的 util 函数waitForElement并且它有效。

export const sleep = async (milliseconds) =>
   new Promise((resolve) => setTimeout(resolve, milliseconds));

/**
 * Wait for element to be available in the UI hierarchy
 * @param {Detox.Element} appElement detox element
 * @param {Number} timeout Timeout in milliseconds
 * @param {Number} maxRetries
 * @returns {Object}
 * {
 *   found: <Boolean>, // Determines if element was found
 *   retryCount: <Number> // Number of tries to find the element
 * }
 */
export const waitForElement = async (appElement, timeout, maxRetries = 5) => {
  let found = false;
  let retryCount = 0;

  while (!found && retryCount < maxRetries) {
    try {
      await expect(appElement).toExist();
      found = true;
    } catch (err) {
      retryCount += 1;
      if (retryCount < maxRetries) {
        await sleep(timeout);
      } else {
        throw err;
      }
    }
  }

  return {found, retryCount};
};

使用示例:

it('should be in home menu', async () => {
    const cancelUpgradeElement = element(by.id('cancelUpgrade'));
    await waitForElement(cancelUpgradeElement, 2000);
    await cancelUpgradeElement.tap();
});
于 2021-12-14T06:54:39.757 回答