Skip to content

Instantly share code, notes, and snippets.

@wswebcreation
Created November 3, 2024 17:33
Show Gist options
  • Save wswebcreation/ee6cc629a3eecf60dc35cd13f302951c to your computer and use it in GitHub Desktop.
Save wswebcreation/ee6cc629a3eecf60dc35cd13f302951c to your computer and use it in GitHub Desktop.
WDIO Native Longpress

Native longPress usage

Adjust the config like this

import { longPress } from "./longPress";

export const config: WebdriverIO.Config = {
  //...
  before: function (capabilities, specs) {
    browser.addCommand("longPress", longPress, true);
  },
  //...
};

And use it like this

import { driver } from "@wdio/globals";

describe("Custom longPress", () => {
  if (driver.isAndroid) {
    it("should close the Android settings do a longPress on the Photos app", async () => {
      await driver.back();
      const photosApp = await $(
        '//android.widget.TextView[@content-desc="Photos"]'
      );
      await photosApp.waitForDisplayed();
      await photosApp.longPress();
      const widget = await $(
        '//android.widget.LinearLayout[@resource-id="com.google.android.apps.nexuslauncher:id/popup_container"]'
      );
      widget.waitForDisplayed();
    });
  }

  if (driver.isIOS) {
    it("should closs the iOS settings and do a longPress on the Settings App", async () => {
      await driver.terminateApp("com.apple.Preferences");
      const filesApp = await $('-ios predicate string:name == "Files"');

      await filesApp.waitForDisplayed();
      await filesApp.longPress();
      await $(
        '-ios predicate string:label == "Edit Home Screen"'
      ).waitForDisplayed();
    });
  }
});
/**
* This file contains a custom implementation of the longPress function.
*/
import logger from "@wdio/logger";
const log = logger("webdriverio");
export interface LongPressOptions {
duration?: number;
x?: number;
y?: number;
}
export const longPress = async function (
this: WebdriverIO.Element,
options?: LongPressOptions
) {
const isNativeMobileApp =
driver.isMobile && (await driver.getContext()) === "NATIVE_APP";
if (!isNativeMobileApp) {
return log.warn(
'The "longPress" function is only supported for native mobile apps in the "NATIVE_APP" context.'
);
}
const defaultDuration = 1500;
// Adjust duration for iOS if it's 1000ms or more, iOS needs to be in seconds
const duration =
driver.isIOS && (options?.duration ?? defaultDuration) >= 1000
? (options?.duration ?? defaultDuration) / 1000
: options?.duration ?? defaultDuration;
const args = {
elementId: this.elementId,
duration,
...(options?.x !== undefined && { x: options.x }),
...(options?.y !== undefined && { y: options.y }),
};
if (driver.isAndroid) {
return driver.execute("mobile: longClickGesture", args);
}
return driver.execute("mobile: touchAndHold", args);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment