它可能不是最好的解决方案,但我创建了一个名为的 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();
});