Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Additional info
When creating Mobile Automation scripts,

If the element type is id:

Code Block
languagejs
var elem : driver.$(id:myElement)

If the element type is accessibility:

Code Block
languagejs
var elem : driver.$(~myElement)

You don't need to add any prefix when using XPath.

While creating Web Automation scripts,

If the element type is id:

Code Block
languagejs
var elem : driver.$(#myElement)

Expand
titleWebdriverIO example Switch Window Handle - Web Test
Code Block
languagejs
// Tüm açık pencereleri al
    var windowHandles = await driver.getWindowHandles();
    await driver.saveScreen();
// 2.tab'e geçiş yap
    await driver.switchToWindow(windowHandles[1]);
    await driver.saveScreen();
    driver.log("*********"+windowHandles[1]);
    await driver.saveScreen();
// Şu anda ana pencerede olduğunuzu doğrulayın
    driver.log(await driver.getTitle());
    
 // Ana pencereye geri dön
    await driver.switchToWindow(windowHandles[0]);
    driver.log("*********"+windowHandles[0]);
// Ana pencerede olduğunuzu doğrulayın
    driver.log("*********"+await driver.getTitle());
Expand
titleJavascript - WebdriverIO example for Mobile Test
Code Block
languagejs
// Find item using id:
  const myElement = await driver.$('id:myElementSelector');

// Click element
  await myElement.click();
**********************************************
// Find element using XPath
  const myElement1 = await driver.$('//xpath/to/element');

// Click element
  await myElement1.click();
**********************************************
// Find an item using Accessibility id:
  const myElement2 = await driver.$('~accessibilityid:');

// Click element
  await myElement2.click();
**********************************************

// Wait for 3 seconds
  await driver.pause(3000)
**********************************************
// Clear and Sendkeys to element
  const element = await driver.$('id:myInputid:');
  await element.setValue("example@mail.com"); // Assigning a value to Input
  await element.clearValue(); // Clearing the content of the input element
**********************************************
// Add a value to an input or textarea element found by given selector.
  let input = await $('.input')
  await input.addValue('test')
**********************************************
// Swipe action with start XY and end XY coordinates
   driver.touchAction([
    { action: 'press', x: 100, y: 200 }, // Starting point
    { action: 'moveTo', x: 100, y: 100 }, // target point
    'release' // Drag action release
  ]);
**********************************************
// Find an item using id:
   const myElement =await driver.$('id:myElementid:');

// Perform a swipe after finding the item
   myElement.touchAction([
    { action: 'press', x: 100, y: 200 }, // Starting point
    { action: 'moveTo', x: 100, y: 100 }, // target point
    'release' // Drag action release
  ]);
**********************************************
// Target a specific location for the swipe action
   driver.touchAction([
    { action: 'press', x: 100, y: 200 }, // Başlangıç noktası
    { action: 'moveTo', x: 100, y: 100 }, // Hedef noktası
    'release' // Sürükleme işlemi serbest bırakma
  ]);
**********************************************
//Get attribute of element and compare the text
   const elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getText();
    or 
   const elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getAttribute("text");
    or
   const elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getAttribute("value");
   if(elem=="Kaydol"){
        await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").click();
    }
**********************************************
//Custom Logging
    driver.log("my custom log)
**********************************************
//You can define a variable in the header and use the variable you define in the steps on the Case Management screen.

    var username = "example"
  
    driver.setValue(variable)
    
    driver.log("**********"+username);

    username = "ahmet mehmet"
    driver.log("******"+username);
**********************************************    
//Take Screenshot

    await driver.saveScreen();
**********************************************
//Assert example with console log

    const myText = await driver.$('(//*[contains(@name,"Kaydol") or contains(@label,"Kaydol")])[2]')
    const text = await myText.getText()
    await driver.log("***********"+text)

    assert(text === 'Kaydol')    
    assert.equal(text,"Kaydol")
********************************************** 
// Assert with example to use Expect    
    const elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getText();


// Compare expected text and actual text.

    expect(elem).to.equal("Atla");
**********************************************   
 
// Expectation: The element exists
    const elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getText();
    expect(elem).to.exist;
**********************************************

// Expectation: The text of the element should be equal to a certain value.

    var elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]");
    expect(await elem.getText()).to.equal('Expected Text');
**********************************************
//Double-click on an element.

    const myButton = await $('id:myButton')
    await myButton.doubleClick()
**********************************************
// Expectation: The element exists
    var elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]")
    assert.ok(await elem.isExisting(), 'Element bulunamadı');
**********************************************    
// Expectation: Element to be visible
    var elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]")
    assert.ok(await elem.isDisplayed(), 'Element görünür değil');
**********************************************
// Expectation: The text of the element should be equal to a certain value
    var elem =await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]")
    assert.strictEqual(await elem.getText(), 'Expected Text', 'Element metni beklenen değere eşit değil');
**********************************************
// Assert with notEqual example
    var text = await driver.$("(//*[contains(@value,'Kaydol') or contains(@name,'Kaydol') or contains(@label,'Kaydol')])[1]").getText();
    assert.notEqual(text,"Giriş")
**********************************************
// In WebdriverIO, you can use the Node.js built-in assert.strictEqual method for strict equality assertions. This assertion method compares two values using the strict equality operator (===), ensuring that both the value and the type are the same.    
    var myText4 = await driver.$('(//*[contains(@name,"Atla") or contains(@label,"Atla")])[1]')
    var text4 = await myText4.getAttribute("name")
    
    var el5 = await driver.$("(//*[contains(@value,'Atla') or contains(@name,'Atla') or contains(@label,'Atla')])[1]");
    var text5 =await el5.getAttribute("name")
  
    assert.strictEqual(text4, text5, `text4 ${text4} !== text5 ${text5}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
Expand
titleisExisting Returns true if element exists in the DOM or appium XML
Code Block
languagejs
Example -1 
  //Is there an element? Is not there ? Example of a custom function that controls

    function clickIfExists(selector) {
      var elementExists =  driver.$(selector).isExisting();
  
      if (elementExists) {
          driver.log(`Clicking on element with selector: ${selector}`);
          driver.$(selector).click();
          // You can add additional actions after clicking the element
      } else {
          driver.log(`Element with selector ${selector} is not present.`);
          // Take another action if the element is not present
          }
      }

// Check if the element exists
    const doesExist = element.isExisting();
    
    if (doesExist) {
      console.log('The element exists.');
    } else {
      console.log('The element does not exist.');
    }
Expand
titleExamples for Web Tests
Code Block
languagejs
Examples for Web Tests   
// Scroll by a certain amount of pixels
  await driver.scroll(0, 500); // Shift 0 pixels horizontally and 500 pixels vertically
**********************************************
// Or scroll up to an element
  const myElement = await driver.$('#myElementid:');
  myElement.scroll();
  
// Scroll to an element on the page.
const element = await browser.$('#targetElement');
await element.scrollIntoView();
**********************************************
//wait until a certain condition is met
  driver.waitUntil(() => myElement.isDisplayed(),
    {
      timeout: 20000, // 20 saniye (in milliseconds)
      timeoutMsg: 'Waiting time exceeded, item still not visible!'
    });
  await myElement.click();
**********************************************
// Finding an item using id:
  const myElement = driver.$('#username2');

// Waiting for the item to exist for a certain period of time
  myElement.waitForExist({
      timeout: 20000, // 20 saniye (milisaniye cinsinden)
      timeoutMsg: 'Bekleme süresi aşıldı, öğe hala görünür değil!'
    });
  await myElement.click();
**********************************************
// Finding an item using id:
  const myElement = driver.$('#username');

// Waiting for the element to be visible for a certain period of time
  myElement.waitForDisplayed({
      timeout: 20000, // 20 saniye (milisaniye cinsinden)
      timeoutMsg: 'Bekleme süresi aşıldı, öğe hala görünür değil!'
    });
  await myElement.click();
**********************************************
// elem.waitForDisplayed(): 

  Waits until the element is displayed.
  This is a WebdriverIO function that handles the waiting logic.

// expect(elem.isDisplayed()).to.be.true: 

  Uses Chai's expect function to assert 
  that the element is displayed. isDisplayed() is a WebdriverIO function that 
  returns a boolean indicating whether the element is currently displayed.
**********************************************
const elem = await driver.$('#your_element');

// Assert that the element is displayed
    await elem.waitForDisplayed();
    expect(elem.isDisplayed()).to.be.true;

    const el = await driver.$('#submit')
    let clickable = await el.isClickable();
    driver.log(clickable); // outputs: true or false
**********************************************
// wait for element to be clickable
    await driver.waitUntil(() => el.isClickable())

//Return true if the selected DOM-element is displayed
    elem =  await driver.$('#submit');
    isDisplayed = await elem.isDisplayed();
    driver.log(isDisplayed); // outputs: true
**********************************************
// Return true if the selected DOM-element found by given selector is partially displayed and within the viewport.
    elem =  await driver.$('#submit');
    isDisplayedInViewport = await elem.isDisplayed();
    driver.log(isDisplayedInViewport); // isDisplayedInViewport: true
 **********************************************   
//Return true or false if the selected DOM-element is enabled.
    elem =  await driver.$('#username1');
    isEnabled = await elem.isEnabled();
    driver.log(isEnabled); // outputs: true
 **********************************************   
//Return true if the selected element matches with the provid:ed one.
    elem =  await driver.$('#username1');
    const sameEl = await driver.$('#user')
    elem.isEqual(sameEl) // outputs: true
  **********************************************  
//Will return true or false whether or not an <option> or <input> element of type checkbox or radio is currently selected.
   let elem = await driver.$('#username1')
   driver.log(await elem.isSelected()); // outputs: false
  ********************************************** 
//Wait for an element for the provid:ed amount of milliseconds to be clickable or not clickable.

    var elem = await driver.$('#username')
    await elem.waitForClickable({ reverse: true });
  **********************************************  
//Wait for an element for the provid:ed amount of milliseconds to be clickable or not clickable.

    var elem = await driver.$('#username')
    await elem.waitForDisplayed({ reverse: true });
   ********************************************** 
//Wait for an element for the provid:ed amount of milliseconds to be clickable or not clickable.

    var elem = await driver.$('#username')
    await elem.waitForEnabled({ reverse: true });
   ********************************************** 
//Wait for an element for the provid:ed amount of milliseconds to be present within the DOM. Returns true if the selector matches at least one element that exists in the DOM, otherwise throws an error. If the reverse flag is true, the command will instead return true if the selector does not match any elements.
    var elem = await driver.$('#username')
    await elem.waitForExist({ timeout: 5000 });
    expect(await elem.getText()).to.be.equal('user')
**********************************************
//

  const el = await driver.$('#username')
    let isDisplayed = await el.isDisplayed();
    driver.log(isDisplayed); // outputs: true or false

  
    if(el !== null) {
        await el.click();
    }

**********************************************
In WebdriverIO, you can use the waitForExist, waitForDisplayed or waitUntil 
functions to wait until an element is found under a certain condition. 
Here are examples of using each function:

// Finding an item using id:
  var myElement = driver.$('#username');

//wait until a certain condition is met
  driver.waitUntil(() => myElement.isDisplayed(),
    {
      timeout: 20000, // 20 saniye (in milliseconds)
      timeoutMsg: 'Waiting time exceeded, item still not visible!'
    });
  await myElement.click();
**********************************************
// Finding an item using id:
  const myElement = driver.$('#username2');

// Waiting for the item to exist for a certain period of time
  myElement.waitForExist({
      timeout: 20000, // 20 saniye (milisaniye cinsinden)
      timeoutMsg: 'Bekleme süresi aşıldı, öğe hala görünür değil!'
    });
  await myElement.click();
  **********************************************
// Finding an item using id:
  const myElement = driver.$('#username');

// Waiting for the element to be visible for a certain period of time
  myElement.waitForDisplayed({
      timeout: 20000, // 20 saniye (milisaniye cinsinden)
      timeoutMsg: 'Bekleme süresi aşıldı, öğe hala görünür değil!'
    });
  await myElement.click();
**********************************************
// elem.waitForDisplayed(): 

Waits until the element is displayed.
This is a WebdriverIO function that handles the waiting logic.
**********************************************
// expect(elem.isDisplayed()).to.be.true: 

Uses Chai's expect function to assert 
that the element is displayed. isDisplayed() is a WebdriverIO function that 
returns a boolean indicating whether the element is currently displayed.

**********************************************
  const elem = await driver.$('#your_element');

// Assert that the element is displayed
  await elem.waitForDisplayed();
  expect(elem.isDisplayed()).to.be.true;
  
  
// momentum webdriver.io execute script with forceClick
var btn = await driver.$(“//*[contains(@class,‘xxx’)]“)
await driver.execute((el) => {
            el.click();
        }, btn);
        
        
// to make sure the page is completely loaded    
  driver.addCommand("pageReady", async () => {
        try {
       
        // document.readyState control when the page loads.
        await driver.waitUntil(async () => {
            const readyState = await driver.execute(() => document.readyState);
            await driver.log("******"+readyState)
            return readyState === 'complete';

        }, {
            timeout: 30000, // Timeout duration (in milliseconds)
            timeoutMsg: 'The page did not load in a certain time.'
        });

        // Once the page is completely loaded you can continue

    } catch {
        //
        await driver.log("************");
    }

});
Expand
titleClose popups on iOS
Code Block
languagejs
try{
    await driver.$("~Allow Once").click();
}catch(error){
await driver.log("************Element is not found***********")
}

try{
    await driver.$("//*[contains(@name,'Allow Once') or contains(@label,'Allow Once')]").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Allow").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Allow").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Only While Using the App").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Allow While Using App").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Not Now").click();
}catch(error){
await driver.log("************Element is not found***********") 
}
try{
    await driver.$("id:Cancel").click();
}catch(error){
await driver.log("************Element is not found***********") 
}

Expand
titleSwipe Method Dynamic Use
Code Block
languagejs
// Using swipe that takes dynamic external parameters.   
Example -1 
  driver.addCommand('swipe', (startX, startY, endX, endY, duration) => {

         driver.touchAction([
            { action: 'press', x: startX, y: startY },
            { action: 'wait', ms: duration },
            { action: 'moveTo', x: endX, y: endY },
            'release'
            ]);
    });
    
 // Replace these coordinates with your actual coordinates
    const startX = 100;
    const startY = 500;
    const endX = 100;
    const endY = 100;

  // Perform swipe with dynamic parameters
    await performSwipe(startX, startY, endX, endY);
   ********************************************** 
    
Example -2

  driver.addCommand('swipeUp', () => {
       
        const {width,height} = driver.getWindowSize();
        const startX = wid:th /4;
        const startY = height * 5/6;
        const endX = wid:th /4;
        const endY = height * 2/6;
    })
Expand
titleTap Method with Dynamic Use
Code Block
languagejs
Example -1
// Using the Tap Method, which takes dynamic external parameters.  
  driver.addCommand('tapClick', (tapX,tapY) => {
      driver.touchAction([
            { action: 'tap', x: tapX, y: tapY },
        'release',
              ]);
    });
    **********************************************
// Tap Method with Dynamic Use 
Example -2
driver.addCommand('tapElem', (elementSelector) => {
    const element =  driver.$(elementSelector);
         driver.touchAction([
           { action: 'press', element },
        'release'
            ]);
    });
Expand
titleUse to Enviroment
Code Block
languagejs
await driver.log(process.env.GSM);
const myButton = await driver.$("//*[contains(@type,'XCUIElementTypeTextField')]")
await myButton.addValue(process.env.GSM);
Expand
titleCommands to start or close a specific application.
Code Block
languagejs
  // Terminate the given app on the device iOS
  await driver.execute('mobile:terminateApp',{ bundleId:"tr.com.ziraat.mobven.enterprise.ziraatpay.test"});
**********************************************
  await driver.execute('mobile:terminateApp',{bundleId: 'com.marsathletic.ios.macfit.app.dev'});
  await driver.pause(2500);
********************************************** 
  await driver.execute('mobile:activateApp',{bundleId: 'com.marsathletic.ios.macfit.app.dev'});
  await driver.pause(2500);
**********************************************
  await driver.execute('mobile:launchApp',{ bundleId:"tr.com.ziraat.mobven.enterprise.ziraatpay.test"});
**********************************************
// Launch a specific application.
  await driver.launchApp({bundleId: 'com.example.MyApp'});
**********************************************
// Launch a specific application.
  await driver.activateApp({'com.example.MyApp'});
**********************************************
  This protocol command is deprecated For iOS, utilize 
  
  await driver.execute('mobile: launchApp', {bundleId: 'com.example.MyApp}),
  
  and for Android:,make use of 
  
  await driver.execute('mobile: activateApp', {appPackage: 'com.example.MyApp'})
**********************************************
//Remove an app from the device.
  await driver.removeApp(appid:)
  
  App id: (package id: for Android:, bundle id: for iOS)
**********************************************  
// Use only Android:
  await driver.resetApp()
********************************************** 
// Use only iOS

await driver.execute("mobile: killApp",{bundleId: 'com.marsathletic.ios.macfit.app.dev'})

**********************************************
await driver.execute('mobile: launchApp', {
    'bundleId:': 'com.marsathletic.ios.macfit.app.dev',
    'arguments': [],
    'enviroment': {
        //
    }
})
**********************************************
await driver.execute("mobile: queryAppState",{bundleId: 'com.marsathletic.ios.macfit.app.dev'})
**********************************************
await driver.execute("mobile:batteryInfo",{bundleId: 'com.marsathletic.ios.macfit.app.dev'})
**********************************************
await driver.execute("mobile:deviceInfo",{bundleId: 'com.marsathletic.ios.macfit.app.dev'})
**********************************************
await driver.execute("mobile:activeAppInfo",{bundleId: 'com.marsathletic.ios.macfit.app.dev'})
**********************************************
Expand
titleSet fake GPS coordinates
Code Block
languagejs
// Set fake GPS coordinates

await driver.execute('mobile: setGeoLocation', { latitude: 37.7749, longitude:-122.4194 });
Expand
titleCustom Method for Example
Code Block
languagejs
driver.addCommand('randomNumber', (min,max) => {
        return Math.floor(Math.random() * (max - min)) + min
    });   
driver.addCommand('randomName', (length) => {

        var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var text = "";
        for (var i = 0; i < length; i++) {
                result += charset[Math.floor(Math.random() * charset.length)];
        }
        
        return text;
    });
Expand
titleTake Screenshot
Code Block
languagejs
driver.addCommand('save', () => {
        return driver.saveScreen()
    });
Expand
titlegetLocation
Code Block
languagejs
const logo = await driver.$('.octicon-mark-github') 
const location = await logo.getLocation(); 
await driver.log(location); // outputs: { x: 150, y: 20 } 
const xLocation = await logo.getLocation('x') 
await driver.log(xLocation); // outputs: 150 
const yLocation = await logo.getLocation('y') 
await driver.log(yLocation); // outputs: 20
Expand
titlepushFile
Code Block
languagejs
// Use the Appium `pushFile` method to push the file to the device
  await driver.execute('mobile: pushFile', {
    path: 'path/to/your/local/file.txt',
    data: 'base64-encoded-file-content',
  });

...