Skip to content

Instantly share code, notes, and snippets.

@nathanchilton
Last active March 30, 2023 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanchilton/acf8c18e69afe72d10e39be828d35d3e to your computer and use it in GitHub Desktop.
Save nathanchilton/acf8c18e69afe72d10e39be828d35d3e to your computer and use it in GitHub Desktop.
Using the Java version of Playwright from within Karate
Feature: Initialize Playwright
Scenario: Set up a starting point for a UI test using Playwright
* def playwright = Java.type("com.microsoft.playwright.Playwright").create()
* def Browser = Java.type("com.microsoft.playwright.Browser")
* def BrowserType = Java.type("com.microsoft.playwright.BrowserType")
* def BrowserContext = Java.type("com.microsoft.playwright.BrowserContext")
* def SelectOption = Java.type("com.microsoft.playwright.options.SelectOption")
* def Page = Java.type("com.microsoft.playwright.Page")
* def Paths = Java.type("java.nio.file.Paths")
* def browser = playwright.chromium().launch((new BrowserType.LaunchOptions()).setHeadless(HEADLESS))
* def browserContext = browser.newContext()
* def page = browserContext.newPage()
# Define a few more objects for waiting until an element is "hidden"
* def WaitForOptions = Java.type("com.microsoft.playwright.Locator.WaitForOptions")
* def WaitForSelectorState = Java.type("com.microsoft.playwright.options.WaitForSelectorState")
* def HIDDEN = WaitForSelectorState.valueOf('HIDDEN')
# Example: * page.locator("nav#save-items").waitFor(new WaitForOptions().setState(HIDDEN))
* page.navigate('https://playwright.dev/java/docs/locators#locate-by-css-or-xpath')
@nathanchilton
Copy link
Author

Karate has a mechanism for using Playwright, but that approach did not work for me. Instead, I just made use of Karate's Java interop capabilities to use the Java version of Playwright from within a Karate scenario.

Actually, I use this bit to initialize Playwright at the beginning of UI tests by calling this scenario and then I can use Playwright almost exactly as described in Playwright's documentation.

* call read("classpath:initialize-playwright.feature")

Note: I set the value of HEADLESS inside of karate-config.js, where it reads in the value from a .env file. You could manually define this or just hardcode a value of true or false in place of the variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment