Katalon Web Test Automation Tutorial


.

Contents:

Katalon Studio is an all-in-one test automation solution for Web, API, mobile, and desktop built for both beginners and expert testers.

Katalon Studio is an integrated development environment (IDE) for automated test generation, where you can create, execute and view reports for your automated test. With both manual view and script view, Katalon Studio is suitable even when you have little programming experience, or you are aready an expert in the automated testing field.


With Katalon Studio, you can do the following:

  • Web testing. See Introduction to Web Testing.
  • Mobile testing for Android and iOS. See Introduction to Mobile Recorder.
  • API testing. See Introduction to API Testing.
  • Desktop app testing. See Introduction to Desktop App Testing.
  • Data-driven testing. See Data-driven Testing with Katalon Studio.
  • BDD testing. See BDD Testing Framework (Cucumber integration).


Download Katalon Studio

GETTING STARTED WITH KATALON STUDIO V7

Getting Started References:

https://docs.katalon.com/katalon-studio/docs/record-web-utility.html 

1. CREATE PROJECT

1. Run Katalon Studio


2. Create new project


Go to menu File/New/Project

Name= Project1
Location= C:\ZT\KatalonStudioProjects\

Press OK



3. TestOps Integration (optional)



Click OK.





4. Project creation done.


2. CREATE TEST CASE (RECORD APPROACH)

1. Create new test case



Go to menu file/new/test case





2. Enter test case information

Name= New Test Case 1

3. Select Record Web button

4. Enter test url

URL= http://demoaut.katalon.com/

Click the Record button when you are ready to record.

5. Observe that the web page is successfully loaded.

Find Make Appointment button.

6. Click Make Appointment button

7. Enter login details using demo account credential

Username = John Doe

Password= ThisIsNotAPassword

Press the Login button

Note:

The recorded steps will be generated automatically in Recorded Actions. When you type in a Password field, Katalon Web Recorder uses the 'Set Encrypted Text' keyword automatically. The input's value will be encrypted to ensure security.

8. Observe that the Make Appointment page is loaded.

9. Find the logout menu and click the logout menu.

10. View the recorded actions

11. Stop the recording

12. Save the script.

13. Script has been saved.

14. Test run the script

REFERENCE

https://docs.katalon.com/katalon-studio/docs/record-web-utility.html#record-a-new-test-case 

Record Using Existing Test Case

Users can be more productive while modifying existing test cases.

Instead of creating a brand new test case whenever there are changes to the UI, risks of overlooking how new changes might affect existing features are now minimized.

1. Open any existing test case to continue recording.

2. Click on the Record icon to open Web Recorder.

Click Yes to continue recording the same test case.

3. All the existing test steps and Test Case variables will be imported to the Recorded Actions and Variables tabs in Web Recorder respectively. You won't need to repeat the test steps having been recorded.

4. Interact with the AUT.

When saving your script, Katalon Studio automatically detects similar existing objects in the Objects Repository and asks you for further action to optimize the Object Repository.

(a) Merge changes into existing objects

(b) Create duplicate objects

(c) Replace existing objects

https://docs.katalon.com/katalon-studio/docs/record-web-utility.html#record-using-existing-test-case 

Rename Page Folders and Elements while Recording

To organize your test scripts in page object pattern, you need to add test objects in the folder corresponding to the page. This will help you reuse and maintain the objects.

https://docs.katalon.com/katalon-studio/docs/create_test_case_using_record_playback.html#rename-page-folders-and-elements-while-recording 

Validate UI elements

Given that you enter an incorrect username or password, you can validate if the website displays an error message indicating a failed login attempt.

Or you can verify if the next screen after a successful login is "right" by verifying if a specific UI element is present.

Run the test and observe the Log Viewer output window.

Note:

In the drop-down list of the Run button, you can find some Run options. The two of them labeled with "Debug" are advanced options for validating recorded script, and saving you from running all test steps over and over again if you have a Katalon Studio Enterprise license:



Run all steps: Execute ALL steps that are enabled on Web Recorder

Debug: Run selected steps: Execute only one or many selected steps.

You can select multiple steps using either Ctrl or Shift key. The selected steps will be highlighted (e.g. steps #2, #6, #9 and #11 are selected for running).

https://docs.katalon.com/katalon-studio/docs/record-web-utility.html#validate-ui-elements 

Note:

VerifyElementPresent can further be responded by Failure Handling:

Katalon Web Recorder Utility's Components

Recorded Actions

Available actions in Katalon Web Recorder Utility is the same as Katalon Studio's built-in keywords. You can add any action, call another test case, and/or use Custom Keywords.

Captured Objects

During your recording, Katalon captures the objects that you have interacted with. When saving test script, Katalon Web Recorder exports a list of objects used in the test case. Learn more about Web UI test objects.

Running Steps In Web Recorder Window


Katalon Studio Tutorial: Using Web Recorder Utility to capture form activities

Creating test cases using Record & Playback

Test recording is the easiest way for new automation testers to start learning test automation. Identifying objects on applications is time-consuming. The Web Recorder Utility function captures your actions being performed on the application and converts them into runnable code in the back-end.

You can quickly automate a few functionalities of your app and save time by recording actions that have to be performed many times in iterative builds. This function supports recording and running the same tests on multiple browsers. This document will show you how to:

  1. Record test with the Record Web function
  2. Rename Page Folders and Elements while runtime recording

Record Test with the Record Web function

Scenario: To make an appointment

  1. Launch the application under test (Example: http://demoaut.katalon.com/)
  2. Click the Make Appointment button
  3. Enter a valid username, password, and click Login
  4. Make an appointment

Follow the below steps to get familiar with the Record & Playback feature for Web UI tests

Step 1: Launch Katalon Studio and click New > Test Case on the main toolbar. Provide a name for your test case and click OK. An empty test case will be created.

Create-Test-Case

Step 2: Click Record Web from the main toolbar.

Record-Web

Step 3: The Record dialog will be displayed.

Web recorder

Step 4: Select a browser, then click Record to start recording the test case.

recording-test-case

Step 5: Once your application has been launched, click on the Make Appointment button. You will be directed to the Login page.

Make-Appointment

Step 6: Enter valid username and password (John Doe and ThisIsNotAPassword), then click Login.

Login-to-Make-Appointment

Step 7: Once the Make Appointment page has been loaded, select the value Hongkong CURA Healthcare Center from the Facility drop down menu.

Make-Appointment-page

Step 8: Select the Apply for hospital readmission checkbox.

Step 9: Then move the cursor to click on the Medicaid checkbox.

Step 10: Click the calendar icon next to Visit Date (Required). Select a date.

Calendar

Step 11: Enter text in the Comment field.

Step 12: Click Book Appointment.

Step 13: You can stop the recording anytime by clicking Stop. Katalon Studio allows users to select the Selection Method for the captured objects. The Basic mode is recommended to manual testers who have just started automated testing. With basic mode, Katalon Studio will automatically generate robust and unique selectors for captured objects.

Advanced testers who want to manually input the selectors have the option to choose between CSS and XPath modes. For more details about Selection Method, refer to this guide.

Katalon Web Recorder

Step 14: When you are done recording, click OK to save the recorded actions into Katalon Studio.

You will be prompted to save captured objects to the Object Repository, which can be reused whenever needed. You can also create a folder to maintain page objects in desired structure. Click OK to continue.

Object-Repository

Step 15: Recorded objects and actions are saved in the test case as shown below.

Recorded-objects

Click Run to execute recorded test cases in your desired browser.

Script Code for Record and Playback

WebUI.openBrowser('')

WebUI.navigateToUrl('http://demoaut.katalon.com/')</p>

WebUI.click(findTestObject('Page_CURA Healthcare Service/a_Make Appointment'))

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (1)/button_Login'))

 

WebUI.selectOptionByValue(findTestObject('Page_CURA Healthcare Service (2)/select_facility'), 'Hongkong CURA Healthcare Center',

 

true)

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (2)/input_hospital_readmission'))

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (2)/input_programs'))

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (2)/div_input-group-addon'))

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (2)/td_3'))

 

WebUI.setText(findTestObject('Page_CURA Healthcare Service (2)/textarea_comment'), 'Katalon')

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (2)/button_Book Appointment'))

 

WebUI.closeBrowser()

Rename Page Folders and Elements while Recording

To organize your test scripts in page object pattern, you need to add test objects in the folder corresponding to the page. This will help you reuse and maintain the objects.

Scenario: Login with valid data

  1. Launch the application under test (Example: http://demoaut.katalon.com/)
  2. Click the Make Appointment button
  3. Enter a valid username, password, and click Login

Step 1: Launch Katalon Studio and click First Test Case on the main toolbar. Provide a name for your test case and click OK. An empty test case will be created.

Change-Element-Name

Step 2: Click Record Web on the main toolbar.

Record-Web

Step 3: The Record dialog will be displayed. Select a browser and click the Record button to start recording the test case.

recording-test-case

Step 4: Once your application has been launched, click on the Make Appointment button. You will be directed to the Login page.

Record-Dialog-Box

Step 6: Rename the page name from "Page_CURA Healthcare Service" to "Page_Home Page."

Step 7: In the Captured Objects frame, select the a_Make Appointment element.

Step 8: Rename the element name from "a_Make Appointment" to "button_Make Appointment."

Web-Recorder-Utility

Step 9: Go back to the recording browser and continue to record. Click Login.

Login-to-Make-Appointment

Step 10: Repeat the same steps above to change the name of the object Login and its folder.

Step 11: Rename the Page name from "Page_CURA Healthcare Service" to "Page_Login."

Web-Recorder-Utility-2

Step 12: You can stop recording by clicking Stop. Click OK to save recorded actions into Katalon Studio.

Step 13: You will be prompted to save the captured objects to Object Repository, which can be reused whenever needed. You can also create a folder to maintain page objects in your desired structure. Click OK to continue.

Objects-repository

Step 14: Recorded objects and actions are saved in the test case as shown below.

Recorded-objects-and-actions

Click Run to execute the recorded test cases in your desired browser.

Source Code:

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject</p>

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

 

WebUI.openBrowser('')

 

WebUI.navigateToUrl('http://demoaut.katalon.com/')

 

WebUI.click(findTestObject('Page_Home Page/button_Make Appointment'))

 

WebUI.click(findTestObject('Page_Login/button_Login'))

 

WebUI.closeBrowser()

Thus we can record the actions being performed using Katalon Studio. However, there are a few actions which cannot be recorded.

What cannot be recorded?

Though recording your tests saves time, we cannot validate some scenarios such as Web Table handling, switching to multiple frames, switching to windows, handling captcha, image recognition, and video playbacks.

You can download the source code here.

For further instructions and help, please refer to Recording WebUI Test and Record and Playback tutorials.

https://docs.katalon.com/katalon-studio/docs/create_test_case_using_record_playback.html 


https://docs.google.com/document/d/10xeMf8Gd8_I0D7f3EUbgEhdmIY-G27XERRn3LPJktnY/edit?usp=sharing


Katalon Studio Tutorial: Synchronizing commands while recording

What is Synchronization?

Synchronization is a mechanism which allows multiple threads to work in parallel. In test automation, the application under test (AUT) and the automation tool we employ should collaborate to progress the test execution. In order to achieve this and avoid execution failures, we need to use synchronization commands. This tutorial shows you how to do just that.

Scenario:  Login with valid credentials

  1. Launch the application under test (URL: http://demoaut.katalon.com/)
  2. Use Wait For Page Load keyword
  3. Use Wait For Element Visible keyword for Make Appointment button
  4. Click on Make Appointment
  5. Use Wait For Element Visible for Login button
  6. Enter valid username, password and click on Login button

At runtime recording, we can add synchronization commands to wait for page load, wait for element present, wait for element visible, etc.

Step 1: Launch Katalon Studio and click on the New Test Case button from the main toolbar. Provide a name for your test case and click OK. An empty test case will be created.

Step 2: Click on Record Web from the main toolbar.

use synchronization commands while recording in Katalon Studio

Step 3: The Record dialog would be displayed, where recorded actions will be shown.

Provide the URL of application under test.

Provide the URL of application under test

Step 4: Select a browser and click on the Record button to start recording the test case

start recording the test case

Step 5: Once your application is launched, move the cursor to 'Make Appointment' and click on the button (wait for Login page gets loaded).

move the cursor to 'Make Appointment'

Step 6: You can add synchronization commands in runtime recording in the 'Recorded Actions' pane. Select a step at which the synchronization commands will be added. Click on Add.

add synchronization commands in runtime recording

Step 7: Click on Add Web UI Keyword

Step 8: The system will add the drop down command

Step 9: Select Wait For Page Load keyword.

Wait For Page Load keyword

Step 10: Here, we have selected 'Wait For Page Load' keyword

Step 11: We need to provide the expected time as an input for the command [Katalon uses the default time of 30 seconds]. Tap on 'Action Data' or 'Input' of Wait For Page Load and give 45 seconds [as you typically need] then click on OK.

Tap on 'Action Data' of Wait For Page Load

Step 12: It should display the Wait For Page Load command with the provided input as shown below. Now Katalon Studio will wait 45 secs for the page to gets fully loaded to execute next command. These synchronization commands avoid execution failures.

Wait For Page Load command

Step 13: You can pause, resume the recording whenever you need it. Let us continue with recording few more actions. Switch to the browser in which you're recording, move to Make Appointment button and click on Make Appointment button.

Make Appointment button

Step 14: Now to wait for specific element to be loaded and to perform action, we need to add 'Wait for Element Present' command before click on 'Make Appointment' button. let us wait for the button loaded in the DOM

Step 15: So here,  we have added two wait commands, one is to wait till page gets loaded and other is wait till element gets displayed as shown below**.** The reason behind adding two waits is that, though page has been loaded sometimes elements won't be present in the DOM (referring to Ajax based applications mainly).

added two wait commands

Step 16: Having said that, we need to provide the expected time as an input for all the wait commands. Tap on Action Data of Wait for Element Present and provide 15 seconds as expected time interval and click on OK Button.

Step 17: Recording pane should look like as shown below**.** Unlike 'Wait for Page Load' command 'Wait for Element Present' command need another parameter as web element for which we are waiting for.

Step 18: To provide web element as a parameter**,** click on Element column of Wait for Element Present, now it will display Captured Objects dialog box. Choose the object and click on OK Button.

Step 19: The recorded actions with synchronization commands should look like as shown below

The recorded actions with synchronization commands

Step 20: Let's continue the recording, in the browser move the cursor to Login Button and click on Login Button.

move the cursor to Login Button and click on Login Button

Step 21: Now add another wait command up above the left click on the login button.

Step 22: Click on Add button and click on Add synchronization point, it will add default command Wait for Element Present.

Step 23: Then we need to change Wait for Element Present to Wait for Element Visible. Double click on action method of Wait for Element Present, then it would display the down arrow, then click on down arrow button it display all the synchronization commands click on wait for Element Visible command [or use others as per you needed].

change Wait for Element Present to Wait for Element Visible

Step 24: Provide expected time as an input forWait for Element Visible command and click on OK Button.

Step 25: Wait for Element Visible command should be displayed with expected time. Similar to Wait for Element Present, we need to provide web element as parameter for this command

Step 26: To provide parameter, click on the element from Element column, it will display the page object dialog box and choose the object of Login Button and click on OK Button.

Step 27: Your recorded test script should be as shown below

Step 28: You can stop recording anytime by clicking on 'Stop'. When you are done with recording, click OK to save recorded actions into Katalon Studio.

Step 29: You will be prompted to save captured objects into Object Repository which can be reused whenever needed**.** You can also create a folder to maintain page objects in desired structure. Click OK to continue**.**

Step 30: Recorded objects and actions are saved in the test case Manual mode as shown below.

Manual mode Katalon Studio

Click on Script Tab to view the generated code. Katalon Studio allows users to modify the script from the script mode as well. All the above recorded actions can be modified in the script mode.

Script code :

WebUI.openBrowser('')

 

WebUI.navigateToUrl('http://demoaut.katalon.com/')

 

WebUI.waitForPageLoad(45)

 

WebUI.waitForElementPresent(findTestObject('Page_CURA Healthcare Service/a_Make Appointment'), 45)

 

WebUI.click(findTestObject('Page_CURA Healthcare Service/a_Make Appointment'))

 

WebUI.waitForElementVisible(findTestObject('Page_CURA Healthcare Service (1)/button_Login'), 45)

 

WebUI.click(findTestObject('Page_CURA Healthcare Service (1)/button_Login'))

 

WebUI.closeBrowser()

It is recommended to add synchronization while recording automation test cases in the manual mode or script mode. It is also a good practice to use wait commands to avoid execution failures. Download source code here.

For further instructions and help, please refer to Recording WebUI Test tutorial.

https://docs.google.com/document/d/1DIDi5rGbwDJm2HH5oBovSxgdQ4cVfMn6wIbAEZkvz6k/edit?usp=sharing


Katalon Studio Tutorial: Katalon (Web Browser) Automation Recorder

Installation Link For Chrome Browser:

https://chrome.google.com/webstore/detail/katalon-recorder-selenium/ljdobmomdgdljniojadhoplhkpialdid 

Katalon Recorder quickstart

Katalon Recorder is the Selenium IDE-compatible record & playback tool for browser automation testing. You can use it to record, debug, execute & manage test cases, and export test suites to multiple programming languages such as C#, Java, Ruby, Python, Groovy, Robot Framework, etc.

While Katalon Recorder is already designed to ease the stress of automation testing for everyone, we want to further assist you in the onboarding process with this quick user guide. Continue reading for all essential information, features, and instructions to make the best use of the tool!

Katalon Recorder User Guide

Katalon Recorder main UI contains four sections as follow:

  • Main Toolbar
  • Test Explorer
  • Test Case Details View
  • Log/Reference/Variable/Self-healing

1. Main Toolbar

Katalon Recorder’s main toolbar contains buttons to help you to manage the web recording process.

Actions sidebar

Action Side Bar

Open Test Suite

Load a test suite from the filesystem to KR

Sample Projects

Add more than a dozen built-in Sample Projects to get started

Export

Export KR tests to Katalon Studio, Selenium WebDriver, New Relics, App Dynamics

Backup Data

Backup your test suites to TestOps to restore them later

Upload Report

Upload your test executions to TestOps to have analytics, report, and insights

Toolbar

Tool Bar

Record

Record your tests

Play

Execute selected single test case

Play Suite

Execute selected test suite

Play All

Execute all test suites

Pause/Resume

Pause and Resume current execution

Stop

Stop recording on the current execution

Report (moved to Action sidebar)

Upload logs to Katalon TestOps to keep track of execution history

Export

Export current test suite/test case to various scripting languages and framework

Speed

Adjust play speed

Setting

Port configuration for Katalon Studio Users. Allow users to change the default port used by Katalon Studio to communicate with the active browser

Help icon

Katalon Recorder Support Resources include: User Manual, Videos, Community, and Free Advanced Automation

Github icon

Go to Github Dashboard

Extended features

Look at your Daily Usage or opt for Essential Product Tours

2. Test Explorer

Test Explore

Test Suites

Show the number of Passed & Failed tests

Dynamic Test Suites

A dynamic test suite lets you execute test cases with certain tags dynamically.

Test Data

CSV and JSON files are fully compatible with Katalon Recorder native commands.

 

Click + to add CSV and JSON files to your workspace.

Extension Script

Extend Katalon Recorder’s functionality by providing custom commands and locators.

Profiles (Global Variables)

Click + to create a new profile in your workspace

 

Add global variables to your profile

Right-click on the profile and choose Use this in a test case

Editing test case

3. Test Case Details View

Katalon Recorder displays the recorded test script in the test case window. All commands and parameters are shown in table format. You can drag and drop any test step to reorganize the test case order

a. Editing Test Case

Edit Test Case step 1

Edit Test Case Step 2

The Command field shows a drop-down menu

In the Command, Target, Value entry fields, you can see the information of the currently selected command, edit the recorded commands, or add new commands in any given step.

The Command field will show a drop-down menu that suggests commands based on the input. Katalon Recorder supports most of the common Selenium commands, including:

  • Actions: Commands that reproduce user interaction on the application under test.
  • Accessors: Commands are used to store the results in variables.
  • Assertions: Commands that verify the application under test behave as expected.

For more details about Selenium commands, refer to this link.

For a more detailed list of support commands, refer to this document.

b. Context Menu

Context menu 1 Context Menu 2

Right-click on test case details views to display the Context menu. Users can perform most of the essential actions for command at any preferred test step:

Manage test cases

Add Command

Insert a new command in the currently selected step

Delete Command

Remove a single selected command

Delete All Command

Remove all commands of the currently selected test case

Copy Command

Copy the currently selected command

Paste Command

Paste a command at a particular test step

Debug

Toggle Breakpoint

Set a breakpoint to stop at a specific command for debugging purposes

Execute

Play this command

Run a single command for prompt feedback

Play from here

Run from a single command till the end of the script

4. Log/Reference/Variable/Self-healing

Log Reference Variable Self Healing 1 Log-Reference-Variable-Self-healing-2

  • Log: This tab shows the real-time report/log of the test execution. All execution errors, information messages, and execution progress are displayed here.
  • Reference: The Reference tab displays the detailed documentation of the selected command. The information helps users to verify the types and number of parameters of each command.
  • Variables: The Variables tab displays detailed information (name, target, and values) on the currently selected command while test execution is in progress.
  • Self-healing: Self-healing automatically detects valid and broken locators to ensure the test script is executed without interruption. For more information, check out this article.

Katalon Recorder FAQs

  • Is Katalon Recorder free?

Katalon Recorder is a free web extension available on ChromeFirefox, or MS Edge store. To install it, head to your browser store, sign in with your Katalon account (free sign-up), and enjoy all features of Katalon Recorder.

Add to Chrome button

Add to Firefox button

Add to MS Edge button

 

  • Does Katalon Recorder have a professional development team?

Katalon Recorder has a dedicated development team that is constantly listening to our users’ needs. We optimize existing features through monthly, sometimes weekly, updates and commit to delivering quality browser automation solutions to individuals and teams at any scale.

For more information on FAQ & Troubleshooting Instructions, visit this document.

Katalon Recorder Release Notes

For more details on previous versions of Katalon Recorder, please visit our Release Notes.

EXERCISE

1. Repeat the steps in “Getting Started For Katalon Studio” (CURA Healthcare Service).

2. Copy the generated codes from Chrome Katalon Recorder.

3. Reopen Katalon previous Project (CURA Healthcare Service).

4. Create a new Test.

5. Paste the copied codes .

6. Run the test.

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint

import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase

import static com.kms.katalon.core.testdata.TestDataFactory.findTestData

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint

import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory

import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as MobileBuiltInKeywords

import com.kms.katalon.core.model.FailureHandling as FailureHandling

import com.kms.katalon.core.testcase.TestCase as TestCase

import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory

import com.kms.katalon.core.testdata.TestData as TestData

import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory

import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository

import com.kms.katalon.core.testobject.TestObject as TestObject

import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSBuiltInKeywords

import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUiBuiltInKeywords

import internal.GlobalVariable as GlobalVariable

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile

import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS

import com.kms.katalon.core.testobject.SelectorMethod

import com.thoughtworks.selenium.Selenium

import org.openqa.selenium.firefox.FirefoxDriver

import org.openqa.selenium.WebDriver

import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium

import static org.junit.Assert.*

import java.util.regex.Pattern

import static org.apache.commons.lang3.StringUtils.join

import org.testng.asserts.SoftAssert

import com.kms.katalon.core.testdata.CSVData

import org.openqa.selenium.Keys as Keys

SoftAssert softAssertion = new SoftAssert();

WebUI.openBrowser('https://www.google.com/')

def driver = DriverFactory.getWebDriver()

String baseUrl = "https://www.google.com/"

selenium = new WebDriverBackedSelenium(driver, baseUrl)

selenium.open("https://katalon-demo-cura.herokuapp.com/")

selenium.click("id=btn-make-appointment")

selenium.click("id=txt-username")

selenium.type("id=txt-username", ("John Doe").toString())

selenium.click("id=txt-password")

selenium.type("id=txt-password", "ThisIsNotAPassword")

selenium.click("id=btn-login")

selenium.click("id=combo_facility")

selenium.select("id=combo_facility", "label=Hongkong CURA Healthcare Center")

selenium.click("id=chk_hospotal_readmission")

selenium.click("id=radio_program_medicaid")

selenium.click("xpath=//section[@id='appointment']/div/div/form/div[4]/div/div/div/span")

selenium.click("xpath=(.//*[normalize-space(text()) and normalize-space(.)='Sa'])[1]/following::td[27]")

selenium.click("id=txt_comment")

selenium.type("id=txt_comment", "sakit")

selenium.click("id=btn-book-appointment")

selenium.click("xpath=//a[@id='menu-toggle']/i")

selenium.click("link=Logout")

https://docs.google.com/document/d/1iyFfCVUTsuzxVo68mSbpzVoooVgSTh9-RgyfPL-dbUk/edit?usp=sharing


Interacting With Web Page

[WebUI] Create and Run Web UI Test Case using Record and Playback

This tutorial demonstrates how to create a Web UI test case with Katalon Studio using Record and Playback.

Go through the scenario "Sign in the shopping page to purchase a tank top" to get familiar with these features. The basic steps are:

  1. Create a new project to store recorded actions.
  2. Interact with the web page.
  • Sign in.
  • Purchase a Tank Top.
  1. Stop recording and Save scripts.

Shopping Cart sample project is available here.

Create and Run your first Web UI test case

Create New Project

  1. In the Test Explorer on the sidebar > click New Project.
  2. In the displayed New Project dialog:
  • Enter project Name.
  • In project Type, select Web.
  • In Project, select Sample Web UI...(Shopping Cart), the Repository URL is filled automatically.
  • Browse a Location to store your project > click OK.

Record

  1. From the main toolbar, click on Web Recorder Utility icon to open the Web Recorder.
  2. In the displayed Web Recorder:
  1. Wait until the browser is launched and ready to interact.
    When you hover an element, the browser highlights and displays that element's correspondent XPath on the top of the page.

    Tip: You can use hotkey to capture objects (pressing the combination of <Command + back quote>). The captured object will be highlighted with a green border.
  2. Interact with the web page. In this scenario, we will sign in and purchase a tank top.
    During your recording, Katalon Web Recorder captures all the objects that you have interacted with. When you enter the Password field, Katalon Web Recorder uses the '
    Set Encrypted Text' keyword automatically. This input value will be encrypted to ensure security.
  3. Once you finish purchasing > click Save script to stop recording and save the captured objects. Katalon Web Recorder exports a list of objects used in the test case.
    Create a new folder or select an existing one in Object Repository > click OK.

    Katalon Studio allows you to continue recording using the existing test case to reduce your effort on modifying existing ones. Learn more

Playback

To playback the recorded scenario:

  1. Select the test case where you saved the recorded actions.
  2. From the main toolbar, select any browser on the drop-down list next to Run.
    Katalon Studio will execute the chosen test case with the recorded steps accordingly.
    Playback

View the test case in Script mode

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint

import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase

import static com.kms.katalon.core.testdata.TestDataFactory.findTestData

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import static com.kms.katalon.core.testobject.ObjectRepository.findWindowsObject

import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint

import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW

import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile

import com.kms.katalon.core.model.FailureHandling as FailureHandling

import com.kms.katalon.core.testcase.TestCase as TestCase

import com.kms.katalon.core.testdata.TestData as TestData

import com.kms.katalon.core.testng.keyword.TestNGBuiltinKeywords as TestNGKW

import com.kms.katalon.core.testobject.TestObject as TestObject

import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

import com.kms.katalon.core.windows.keyword.WindowsBuiltinKeywords as Windows

import internal.GlobalVariable as GlobalVariable

import org.openqa.selenium.Keys as Keys

WebUI.openBrowser('')

WebUI.navigateToUrl('https://demo-store.katalon.com/')

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/svg_Zack Market_svg-inline--fa fa-user fa-w-14'))

WebUI.setText(findTestObject('Object Repository/shoppingCart/Page_Zack Market/input_Email_email'), 'thuy.ngo@katalon.com')

WebUI.setEncryptedText(findTestObject('Object Repository/shoppingCart/Page_Zack Market/input_Password_password'), 'GklqZBguAPQ=')

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/input_Password_button_btn__2lzmo'))

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/div_All Products_search_auto__TZ-uB'))

WebUI.setText(findTestObject('Object Repository/shoppingCart/Page_Zack Market/input_All Products_auto_input__2ud9e'), 'tank top')

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/span_Tank Top'))

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/img_Clear All_card-img-top'))

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/img'))

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/span_Buy Now'))

WebUI.click(findTestObject('Object Repository/shoppingCart/Page_Zack Market/span_Confirm checkout'))

WebUI.closeBrowser()

REFERENCE:

https://docs.katalon.com/katalon-studio/tutorials/webui-create-test-case.html#create-and-run-your-first-web-ui-test-case 


https://docs.google.com/document/d/1JkVjKOtD4k6kssoT_o0FKB2t7B_PNYHXbdEz-3UShiM/edit?usp=sharing


Analyzing Test Case And Debug

[WebUI] Analyze Test Execution Logs and Debug the Test Case

After executing a Test Case, Katalon Studio provides users with comprehensive execution logs in the Log Viewer. Users can quickly investigate the logs to pinpoint the root causes of any issue and correct the Test execution with Debug utilities.

This tutorial shows you how to analyze execution logs of a failed Test Case in the Log Viewer and debug the Test Case.

Here we reuse the Test Case ("Sign in the shopping page to purchase a tank top") from the tutorial [WebUI] Create and Run Web UI Test Case using Record and Playback.

You can download the sample project here: Shopping Cart Tests.

In our example, the Test Case fails to find a Web element due to an unexpected change in the application under test (AUT). We look for the failed steps in the execution logs, find the root cause, correct the step, and resume execution using the Run from here Debug utility.

Notes:

To use the Debug utility, you need to configure Katalon Studio to NOT terminate browser session when execution finishes. For detailed instructions, refer to this guide: Execute and Debug a Test Case.

Analyze Test execution logs in Log Viewer

After executing the Test Case, Katalon Studio displays the results in the Log Viewer as follows:

Test Execution overview

Here we use the Tree View mode of the Log Viewer to analyze the logs. This mode displays execution logs in a structural way that helps users trace the Test execution and locate failed steps quickly.

Follow these steps to analyze the logs:

  1. Switch to the Tree View. Toggle on the Tree View button on the top-right corner of the Log Viewer.
    Tree View button
    The Tree View displays the execution logs in a tree-like structure on the left pane. Each node in the tree corresponds to a step in the Test Case, and failed steps are marked in red.
    Tree View Structure
    On the right pane, the view displays detailed log messages of each step.
    Log Message Pane
  2. To view warning messages of the failed step, click on the expand icon on the left of the step.
    Here the warnings indicate that Katalon Studio fails to find a Test Object with a specific XPath.
    Log Message Pane
  3. To view the detailed log message, click on the step. The log message is displayed on the right pane.
    Tree View Click on step
    In the root cause section, the message shows an exception: 
    com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id ... not found.
    Root cause section
    To learn how to troubleshoot common exceptions in Web tests, you can refer to this document: Troubleshoot common exceptions when executing web tests.
    Below the root cause section, the message displays the failed step in the form of Test Script.
    Error Script
    From the details provided, we know that Katalon Studio cannot locate the sign-in button with the id 
    'Object Repository/Page_Zack Market/input_Password_button_btn__2lzmo' and the Object Locator //*[@value = 'Signing_in'].

Notes:

  • Execution logs of Test Cases are preserved only in the running session of Katalon Studio. Once you reload Katalon Studio, the logs will disappear.

Debug the Test Case

After finding the root cause, we update the Test Object with a new XPath, and use the Run from here Debug utility to resume the Test execution.

Update the Object Locator

Because a deprecated Object Locator causes the error, we can find the new Object Locator using the browser's Inspector tool.

In our example, we use the Inspector tool to get the XPath of the corresponding Web element.

Follow these steps:

  1. To get the new XPath, in the running browser instance, right-click on the target web element, and select Inspect.
    Here we right-click on the Sign-in button that causes the error.
    Error Script
  2. In the inspector window, the selected element is highlighted, indicating the target element's location in the HTML DOM. Right-click on the highlighted line and select Copy > Copy XPath.
    Error Script
  3. Add the new XPath to the Test Object. Open the Test Object, in the Test Object view, specify XPath as the Selection Method and paste the copied XPath from step 2 in the Selected Locator editor.
    Error Script

Resume the Test execution

After adding the new XPath to the Test Object, we use the Run from here Debug utility to resume Test execution without re-executing the entire Test Case.

Follow these steps to resume the Test execution:

  1. Resume executing from the failed step. Open the Test Case, right-click on the failed step, and select Run from here > The running browser session.
    Error Script
  2. After the Test execution is completed, verify the results in the Log Viewer.
    Error Script

See also:

REFERENCE:

https://docs.katalon.com/katalon-studio/docs/execute-a-test-case-or-a-test-suite.html#debug-from-here 



Setting Default (Element) Selection Methods In Katalon Studio

Selection Methods for Web Tests

This article guides you through choosing different strategies to locate WebUI objects in Katalon Studio.

Configure Test Design

To set the default selection method used in the Spy/Recorder of a project, do as follows:

  1. Open Katalon Studio, then go to:
  • From 7.6.0 backward: Project > Settings > Test Design > Web Locators.
  • From 7.6.0 onwards: Project > Settings > Test Design > Web UI.
    web UI settings
  1. Under the line Default element locator value of test objects generated by Recorder or Spy, select one of these provided options:
  • XPath: Once a test object is captured using Spy/Recorder, a set of XPath locators is generated. The first value is the object's default XPath locator.
  • Attributes
  • CSS
  • Image
  1. If you choose XPath or Attributes, you need to configure additional settings. To learn more, see below:

Configure XPath

You can prioritize XPath locators by dragging and dropping the XPath locators list. To locate the elements, Katalon Studio uses the first XPath as default. If the default XPath fails, the remaining XPaths of the list are leveraged to locate the element.

To return to the default order, click Reset Default.

Below is a list of XPath capture strategies:

XPath capture strategy

Description

Example

xpath:link

Build XPath locators for the link element.

//a[contains(text(), 'Katalon Studio')]

xpath:img

Build XPath locators for the image element.

//img[@alt="Katalon logo"]

xpath:attributes

Build XPath locators based on the tag name and attributes of the selected element.

There are 5 preferred attributes to build element locators: ['id', 'name', 'value', 'type', 'action', 'onclick'].

If the element has more than one of those attributes, the locator combines the attributes with an operator.

//div[@id="search"]

//select[@id="cars" and @name="cars"]

//input[@type="submit" and @value="Submit"]

xpath:customAttributes

Build XPath locators based on the tag name and attributes of the selected element. The XPath value combines one or more attributes of all default and customized attributes. (Available from version 8.2.5)

//<tagname>[@id='1234' and @custom1 = 'a1' and @custom2 = 'a2' and @custom3 = 'a3' and @custom4 = 'a4']

//div[@id="search" and @custom1 = 'a1']

//select[@id="cars" and @name="cars" and @custom1 = 'a1' and @custom2 = 'a2']

//input[@type="submit" and @value="Submit" and @custom2 = 'a2' and @custom3 = 'a3' and @custom4 = 'a4']

xpath:idRelative

Build relative XPath locators from the nearest parent that has id attributes.

//div[@id="search"]/a

//select[@id="cars"]/div/div[2]/input[@type="submit"]

xpath:href

Build XPath locators of an element that has href attributes and matches or contains a given value.

//a[@href='https://katalon.com']

//a[contains(@href, 'katalon')]

xpath:position

Build absolute XPath locators of a selected element.

/html/body/div[1]/div[1]/div/div[3]/div[2]/div

/html/body/section/div/div[2]/div[5]/div[2]/div/div/div[2]/table/tbody/tr[13]/td[1]/div/a/span[3]/span

xpath:neighbor

Build XPath locator based on the more robust neighbors of the selected element.

(.//*[normalize-space(text()) and normalize-space(.)=’How AI can save our humanity’])[2]/preceding::div[3]

dom:name

Build XPath locator based on DOM (Document Object Model). This applies only to elements within a named form.

"document.forms["home"].elements["userName"]"

Configure Attributes

You can select the attributes used for detecting an object.

  • To return to the default setting, click Reset Default.
  • To add new attributes, click Add.
  • To delete an attributes, select the attributes and click Delete.
  • To delete all attributes, click Clear.

configure attribute

Switch Selection Method in an object view

In an object view, you can switch from one selection method to another. The detailed content of each selection method is saved automatically.

attributes

  • Selection Method: Choose an object locating strategy among XPath, Attributes, CSS, or Image.
  • Selected Locator: Input the desired XPath or CSS locator manually.
  • Object's Properties: Check only the preferred properties of an object.

XPath

object view

For better object recognition, Katalon Studio supports Smart XPath (a.k.a Relative XPath). If an element cannot be consistently located using its direct attributes, Katalon Studio identifies the element by using its more robust neighbors. This method is visually intuitive as it reflects the way users often identify a visible element on the user interface.

Working with XPath, you can:

  • Set the priority of XPath locators.
  • Decide which object properties are used to recognize objects.
  • Override the global settings in a specific object. To do so, open an object view and configure a selection method used for this object in particular.

If XPath is set as the default selection method when spying and recording, Katalon Studio generates a list of Smart XPaths automatically.

Learn more about XPath with this guide: Detecting objects with XPath.

object spy

Attributes

A test object is typically built up by several properties. During test execution, Katalon Studio uses them to detect an object.

If Attributes is set as the default selection method during spying and recording, Katalon Studio automatically generates XPath locators that combine all the selected object properties to locate that object. In the Detect object by? column of the Object's Properties table, you can check/uncheck preferred properties.

attributes

CSS

To manually input your CSS locator of a test object, open an object view and select the CSS option. In the Selected Locator, enter a CSS locator value.

CSS

Change the CSS selector of an object at runtime

To change the CSS value of a test object at runtime, use the following code snippet:

import com.kms.katalon.core.testobject.SelectorMethod

TestObject to = findTestObject('your_test_object_id')

//Change value of CSS selector

to.setSelectorValue(SelectorMethod.CSS'your_desired_value')

//Change selection method from another selector to CSS selector

to.setSelectorMethod(SelectorMethod.CSS)

See also:

Image

image

From version 7.2.2 onwards, Katalon supports visual object recognition. You can learn more about how to create image property for an object at Web Image-based Testing.

See also

acceptInsecureCerts / Boolean / true

https://docs.google.com/document/d/1d3tzyqswF6JTfgTLhHZSLJJQWKmGDhDzxp45eR4Wo70/edit?usp=sharing


Detecting objects with XPath

With any application under test (AUT), the detection of UI elements is crucial to automated testing. However, identifying them manually requires much time and experience in HTML.

This task becomes even more challenging for elements that could not be identified by their common attributes, elements that change dynamically, or elements that are located deep within another element (nested elements).

This article shows you how to use XPath in Katalon Studio to deal with nested elements and dynamic elements.

What is XPath?

XPath stands for XML Path Language. In an XML document, XPath uses path expressions to navigate through elements, attributes, and select nodes or node-sets.

On a webpage using the HTML DOM (Document Object Model) structure, you can also use XPath to find the location of any element. To learn more about HTML DOM, you can refer to the W3schools documentation: What is the HTML DOM?

There are two types of XPath: absolute XPath and relative XPath (smart XPath).

Absolute XPath

XML documents are treated as trees of nodes, in which the topmost element of the tree is the root element.

Absolute XPath is the path starting from the root. An absolute XPath starts with HTML and forward-slash (/).

For example: /html/body/div[1]/div[1]/div/div[3]/div[2]/div

In Katalon Studio, the XPath capture strategy for absolute XPath is xpath:position. Using absolute XPath is a simple way to solve the problem when dealing with dynamic elements. However, if something changes in the structure of your web page, this XPath might fail. Therefore, absolute XPath is not recommended for detecting dynamic elements.

Relative XPath

You might want to use the relative XPath method to observe a pattern in the attribute values like ID or Class of the web element. Relative XPath (smart XPath) is the path that starts from the middle of the HTML DOM structure. Unlike the absolute XPath that starts from the root, relative XPath starts with the double forward-slash (//), which means it can search for the element anywhere on the webpage. Therefore, you can start from the middle of the HTML DOM structure without writing a long XPath. For example: //a[contains(text(), 'Katalon Studio')].

You can find a list of XPath capture strategies in Katalon Studio using relative XPath in this document: Configure XPath.

How to identify nested elements?

What is a nested element?

Elements can contain other elements. Nested elements are children of their parent container.

For example, the download link in the script below is an element nested in another.

<div class="container">

        <div class="navbar-collapse navbar-right">

                <div class="nav-bar-decorated">

                        <ul>

                                <li><a class="pbtn-download" href="#katalon-download">Download</a> <!-- Deeply nested element  --></li>

                        </ul>

                </div>

        </div>

</div>

It is difficult to identify a nested element, such as the <a> element in the script above. To define the XPath manually, we need to have solid knowledge about the DOM structure of the webpage.

Identify nested elements using XPath

Identifying XPath is an effective way to find nested elements that cannot be identified by common properties such as ID, name, or class. Katalon Studio can generate and optimize XPath for HTML elements, regardless of how deeply nested they are. You can use these XPaths to identify elements without searching through the DOM tree.

The example below illustrates how Katalon Studio generates and optimizes XPath automatically when you spy on the Make Appointment object (a nested element).

detecting elements with Xpath by Katalon Studio

Deal with dynamically changing elements

What is a dynamic element?

One of the challenging and time-consuming tasks in test automation is to modify test scripts when the AUT is changed, especially in the early stages of software development. Developers may change identifiers and elements quite often from one build to another. In addition, during the execution, the AUT elements may change dynamically.

Dynamic web elements are elements whose IDs and any other attributes like class names or values keep changing when you refresh the page. Dynamic elements are database-driven or session-driven. For example, when you edit an element in a database, it changes a number of areas of the application under test.

Deal with dynamic elements using XPath

To deal with dynamic elements, you might not want to use absolute XPaths for these elements in test cases. Instead, you might want to use relative XPaths based on specific patterns.

XPath axes are used to search for the multiple nodes in the XML document from the current node context. Katalon Studio supports all XPath axes. The table below shows some common methods you can use to detect dynamic elements:

Method

Description

Example

Checking Multiple Attributes

Add more than one condition to search element using XPath.

//*[@id='btn-login'][@type='submit']

Index

Specify a given tag name in terms of the index value you wish to locate. Use this when more than one element is present in the DOM with similar attributes, and it becomes difficult to search for them.

//div[@class='form-group']//select[1]

Chained XPath

Use multiple XPath expressions and chain them.

//section[@id='appointment']//span[@class='glyphicon glyphicon-calendar']

Contains()

Use the Contains() method to detect dynamic elements that contain static values.

//button[contains(@id, 'btn-login')]<

Last()

Last() is a method used in an XPath expression. It is used to get the very last node.

//ul[@class='list-inline']/li[last()]

Start-with()

The Start-with method finds the element using the starting text of an attribute. This method is useful when the first part of the attribute value is fixed (static), and the rest is dynamic.

//h3[starts-with(text(),'We Care About')]

Preceding

Select all nodes that come before the current node.

//*[@id='btn-login']//preceding::input

Following

Select all elements in the document following the current node( ).

.//*[@id='txt-username']//following::input

Following-sibling

Select the following siblings of the context node.

.//*[@id='txt-username']//following::input

Ancestor

Select all ancestors (parent, grandparent, etc.) of the current node.

//ul[@class='list-inline']/ancestor::div

Child

Select all children of the current node.

//ul[@class='list-inline']/child::li

Descendant

Select all descendant (child node, grandchild node, etc.) of the current node.

//ul[@class='list-inline']/descendant::li

For more information on XPath axes, refer to the W3school documentation: XPath Axes.

To learn how to find object locators in Katalon Studio, see Spy Web Utility.

Next step:

Learn how to input and edit XPath or CSS objects to identify objects on Web UI via Spy Web Utility: Generating reliable object selector using Spy Web utility.


https://docs.google.com/document/d/1YfxAPfkzECHSY2-W99V66EhBkP8ZFCofSRZhW56jV7Y/edit?usp=sharing


Generating reliable object selector using Spy Web utility

This article shows you some examples of generating reliable object selectors using Spy Web Utility.

Spy Web Utility provides an intelligent object capturing capability on websites. To learn more about this utility, see Spy Web Utility.

There are two widely used selectors: CSS and XPath. Locators are object attributes that are used to build up XPath or CSS selectors. Locators help find and identify elements on the web page under test.

Based on the selected method, you can edit the Selected Locator to adjust the current selector of an object or manually add a selector using either an XPath or a CSS selector.

With the CSS or XPath mode of the Selection Method, you can further input and edit XPath or CSS objects to identify objects on web UI.

Below are some web element locators:

Web element locators

Description

Id

Select elements with the specified @id attribute.

Name

Select the first element with the specified @name attribute.

Link text

Select links (anchor tag) element which contains text matching the specified link text.

Partial link text

Select links (anchor tag) element which contains text matching the specified partial link text.

Tag name

Locate elements using a tag name.

Class name

Locate elements using a class name.

CSS

Select elements using CSS selectors.

XPath

Locate elements using an XPath expression.

How to find object locators?

You can capture objects, get web element XPath or CSS locators, and manually input XPath or CSS object selectors using Spy Web Utility. Spy Web Utility provides instant feedback by auto-detecting and highlighting all elements that match with the provided selector.

In this section, we will illustrate how to use the Spy Web Utility to find object locators.

  1. Open or create a new project. From the main toolbar, click on the Spy Web icon.
    spy web utility
    The Object Spy window displays.
  2. In the URL section, input the URL of the website you want to test. We use our demo page in this example: http://demoaut.katalon.com/
    object spy dialog
  3. To choose a browser, click on the dropdown icon of the Start button. For this example, we choose a new Chrome browser.
    choose browser
  4. Click Start. Katalon Studio opens a new Chrome browser and navigates to the demo website.
  5. To capture test objects, first, hover the mouse over them. The focused web object is highlighted in red.
    capture object
    Then, by pressing <Alt + `> or right-clicking and choosing Capture Object, the focused object is captured and added to the Captured Objects list.
    Katalon Studio automatically captures all available properties of the objects. You can change the folder name and edit the value of any properties.
    selected locator
    In the Selection Method section, you can choose XPath, Attributes, CSS, or Image to locate captured objects.
  6. In the Selected Locator section, you can manually input your XPath, then click Verify and Highlight. Katalon finds elements that match your XPath locator and highlights them on the web page.
    A single locator might identify many elements because a web page can have many elements that use the same formats and styles. The next section will guide you on how to create unique locators to find complex or dynamic elements. See below: 
    Working with XPath selector.

https://demo-store.katalon.com/ 

  1. To save objects to the Objects Repository, click on Save. Then, select a folder to add the captured objects into. Click OK when done.
    selected locator

Working with XPath selector

The following guide shows how to leverage Katalon Studio Spy Web Utility to locate web elements with XPath selector.

These XPath axes methods are used to find complex or dynamic elements.

In the examples below, we are using our demo page: http://demoaut.katalon.com/

You can find our web sample project available to be downloaded here: Katalon Web Automation Sample Project.

Checking Multiple Attributes

You can identify an element with the combination of multiple attributes to build a unique locator. This method is useful when an element has multiple attributes, but using only one attribute cannot create a unique locator.

For example, you can identify the login button with multiple attributes, like @id and @type, to locate the Login button.

XPath:

//*[@id='btn-login'][@type='submit']

multiple attributes

Index

Specify a given tag name in terms of the index value you wish to locate. Use this when there are more than one element present in the DOM with similar attributes and it becomes difficult to search them.

For example, you want to locate the first dropdown in a page.

XPath:

//div[@class='form-group']//select[1]

index

Chained XPath

You can use multiple XPath expressions and chain them.

For example, use the chained XPath to find the calendar icon in the appointment section.

XPath:

//section[@id='appointment']//span[@class='glyphicon glyphicon-calendar']

chained

Contains()

You can use the Contains() method to detect dynamic elements that contain static values.

Example:

Use the Contains() method to find the login button that contains the id: "btn-login".

XPath:

//button[contains(@id, 'btn-login')]

contain

Last()

Last() is a method used in an XPath expression. It is used to get the very last node.

Example:

There are 3 social icon links, and you want to get the 3rd item by using Last().

XPath:

//ul[@class='list-inline']/li[last()]

last

Start-with()

The Start-with method finds the element using the starting text of an attribute. This method is useful when the first part of the attribute value is fixed (static), and the rest is dynamic.

Example:

To find the line: "We Care About Your Health", use the Starts-with() method to find the line that starts with "We Care About".

XPath:

//h3[starts-with(text(),'We Care About')]

start with

XPath axes methods

These XPath axes methods are used to find complex or dynamic elements.

Following
Selects all elements in the document following the current node( ).
Example:
By using the following method, you can identify the Password text box, which is located after the Username name field.
XPath:
.//*[@id='txt-username']//following::input


  • following

Ancestor
This method selects all ancestors (parent, grandparent, etc.) of the current node.
Example:
In the screenshot below, you want to get the ancestors of the 
ul tag highlighted in red.
XPath:
//ul[@class='list-inline']/ancestor::div


  • ancestor

Child
Select all children of the current node.
Example:
Using the child method, you can identify all social links as shown in the below screenshot.
XPath:
//ul[@class='list-inline']/child::li


  • child

Preceding
Select all nodes that come before the current node.
Example:
Using the preceding method, you can identify all nodes that come before the Login button.
XPath:
//*[@id='btn-login']//preceding::input


  • preceding

Following-sibling
Select the following siblings of the context node. Siblings are at the same level as the current node, as shown in the screen below. It finds the element after the current node.
Example:
By using the following-sibling method, you can identify the Password text box which located after the Username name field.
XPath:
.//*[@id='txt-username']//following::input


  • following-sibling

https://docs.google.com/document/d/1Cw_rUoOGs_06KEeSKHz5mSOxFWe9r65bw2bF-VDa8BE/edit?usp=sharing


Post a Comment

0 Comments