Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept alerts on Android using Appium and React Native?

I have a React Native application that is being tested using jest + Appium Jest launch the tests to run on real devices, for both Android and IOS.

I'm using Appium and wd library for the webdriver API.

I need to accept an alert on the screen for both platforms.

for IOS it seems that using the following code works:

await driver.elementByAccessibilityId('OK').click();

However, it doesn't work for Android.

After googling the solution I came to this topic: How to accept this alert in appium?

The solution indicated there uses the Java client tho:

driver.switchTo().alert().accept();

I have tried a similar solution in my code, but it raises an error:

driver.switchTo is not a function

Which sent me to this issue discussion: https://github.com/webdriverio/webdriverio/issues/1733

It is from 2016, and apparently there's no workaround for the Javascript client? Or did I misunderstood it? I also have tried to add autoAcceptAlerts into the capabilities, no success.

My configuration:

   import wd from 'wd';

   const conf = {
        platformName: 'Android',
        deviceName: 'Galaxy S8',
        app: '/<mypath>/app/build/outputs/apk/debug/app-debug.apk',
        platformVersion: '9',
        autoGrantPermissions: 'true',
        autoAcceptAlerts: 'true',
    }

    const driver = wd.promiseChainRemote('localhost', PORT);

   beforeAll(async () => {
    await driver.init(config);
    await driver.sleep(2000); // wait for app to load
   })

   // await driver.switchTo().alert().accept() // My Attempt 
   // await driver.elementByAccessibilityId('OK').click();

Any idea how can I make it work on Android?

like image 839
dfranca Avatar asked Oct 31 '25 18:10

dfranca


1 Answers

You need to change the context of the driver in order to be able to interact with native apps' alerts. You can use the below line of code in order to change the context to the first alert on the screen.

appiumDriver.context(appiumDriver.getContextHandles().toArray()[1].toString());
like image 130
Sharaf Avatar answered Nov 02 '25 07:11

Sharaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!