Skip to content

Instantly share code, notes, and snippets.

@heyrmi
Created August 4, 2024 08:43
Show Gist options
  • Save heyrmi/db796dbd889754b93de752220f27432a to your computer and use it in GitHub Desktop.
Save heyrmi/db796dbd889754b93de752220f27432a to your computer and use it in GitHub Desktop.
import { browser, $ } from '@wdio/globals'
import { expect } from '@wdio/expect-webdriverio'
describe('WebdriverIO API Overview', () => {
before(async () => {
await browser.url('https://example.com')
})
it('demonstrates WebdriverIO APIs', async () => {
// 1. Browser Navigation
await browser.url('https://webdriver.io')
await browser.back()
await browser.forward()
await browser.refresh()
const title = await browser.getTitle()
console.log(`Page title: ${title}`)
// 2. Element Selection
const searchInput = await $('#search_input_react')
const links = await $$('a')
const customElement = await $('custom-element-tag')
// 3. Element Interactions
await searchInput.setValue('WebdriverIO')
await $('button[type="submit"]').click()
await $('select').selectByVisibleText('Option Text')
await $('input[type="checkbox"]').click()
// 4. Element State
const isDisplayed = await searchInput.isDisplayed()
const isExisting = await searchInput.isExisting()
const isClickable = await searchInput.isClickable()
// 5. Element Properties
const text = await $('h1').getText()
const attribute = await $('img').getAttribute('alt')
const property = await $('input').getProperty('value')
const cssProperty = await $('div').getCSSProperty('color')
// 6. Waiting
await browser.waitUntil(async () => {
return (await $('button').isClickable())
}, {
timeout: 5000,
timeoutMsg: 'Button was not clickable after 5s'
})
// 7. Browser Windows
await browser.newWindow('https://webdriver.io')
const handles = await browser.getWindowHandles()
await browser.switchToWindow(handles[1])
await browser.closeWindow()
await browser.switchToWindow(handles[0])
// 8. Alerts
await browser.acceptAlert()
await browser.dismissAlert()
await browser.sendAlertText('Hello WebdriverIO')
const alertText = await browser.getAlertText()
// 9. Frames
await browser.switchToFrame(await $('iframe'))
await browser.switchToParentFrame()
// 10. Executing JavaScript
const browserName = await browser.execute(() => {
return window.navigator.userAgent
})
console.log(`Browser name: ${browserName}`)
// 11. File Upload
const filePath = '/path/to/file.jpg'
await $('input[type="file"]').setValue(filePath)
// 12. Screenshots
await browser.saveScreenshot('./screenshot.png')
await $('button').saveScreenshot('./button-screenshot.png')
// 13. Network Interception
await browser.mock('**\/api/endpoint', {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'mocked value' })
})
// 14. Element Location and Size
const location = await $('button').getLocation()
const size = await $('button').getSize()
// 15. Page Scrolling
await $('footer').scrollIntoView()
await browser.execute(() => window.scrollTo(0, 500))
// 16. Cookies
await browser.setCookies([
{ name: 'session_id', value: '12345' }
])
const cookies = await browser.getCookies()
await browser.deleteCookies(['session_id'])
// 17. Local Storage
await browser.execute('localStorage.setItem("key", "value")')
const localStorageItem = await browser.execute('return localStorage.getItem("key")')
// 18. Mobile Specific Commands (if using mobile capabilities)
// await browser.touchAction([
// { action: 'press', x: 100, y: 200 },
// { action: 'moveTo', x: 300, y: 400 },
// 'release'
// ])
// 19. Keyboard Actions
await browser.keys(['Control', 'a'])
await browser.keys('Delete')
// 20. Mouse Actions
await $('button').moveTo()
await browser.performActions([{
type: 'pointer',
id: 'mouse',
parameters: { pointerType: 'mouse' },
actions: [
{ type: 'pointerMove', duration: 0, x: 100, y: 100 },
{ type: 'pointerDown', button: 0 },
{ type: 'pointerUp', button: 0 }
]
}])
// 21. Element Waiting
await $('button').waitForDisplayed({ timeout: 5000 })
await $('button').waitForClickable({ timeout: 5000 })
await $('div').waitForExist({ timeout: 5000 })
// 22. Custom Commands (defined in wdio.conf.ts)
// browser.addCommand('myCustomCommand', function () {
// console.log('This is a custom command')
// })
// await browser.myCustomCommand()
// 23. Assertions
await expect($('h1')).toHaveText('Welcome to WebdriverIO')
await expect($('button')).toBeClickable()
await expect(browser).toHaveTitle('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js')
// 24. Timeouts
await browser.setTimeout({ implicit: 5000 })
await browser.setTimeout({ pageLoad: 10000 })
await browser.setTimeout({ script: 60000 })
// 25. Browser Capabilities
const capabilities = await browser.capabilities
console.log('Browser capabilities:', capabilities)
})
// Example of handling a test hook error
afterEach(async function() {
if (this.currentTest.state === 'failed') {
// Take a screenshot or perform other actions on test failure
await browser.saveScreenshot(`./errorShot_${this.currentTest.title}.png`)
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment