Automate GET Request API and Keypress using Playwright

Tutorial 14​​ ​​ Keypress​​ and GET Request API testing​​ in Playwright​​ 

What you will Learn​​ in this​​ blog:

  • Keypress in​​ PW

  • Automate API GET Request

  • Code snippet

Keypress​​ in PW

Launch​​ https://the-internet.herokuapp.com/key_presses​​ ​​ ​​ 

Bring​​ cursor in the highlighted text area and press ‘Tab’ key. We would notice ‘You Entered: TAB’ text written below the text field

Let us see how we can automate this use case.

Let us inspect this field, notice that it can be located using the ‘id’​​ 

Next, launch​​ 

https://playwright.dev/docs/input#keys-and-shortcuts​​ 

Notice that we have​​ ‘press’​​ method that we can use to simulate pressing a keyword

These are some of the keys that we can in with the method

So line#7 uses one of the keys ‘F1’

Save and execute.​​ 

Notice below F1 key was pressed

Similarly, we can try with other keys.

Automate API GET Request

Launch​​ https://reqres.in/​​ 

Click GET request shown against SINGLE USER.​​ 

Notice that the response is 200 (viz the GET request was successfully processed by the server)

Also notice the ‘Request’ uri that is shown above​​ viz​​ /api/users/2.

Let us see how to validate the response using PW.

Notice below the change in syntax to handle api requests

Also, note below that our url is composed of ‘base url’ plus ‘uri’

So our script loks like below

Save and execute.

Notice below that our test gets passed. This means that we received status code 200 in our response

Let us change the response code to 404

Save and execute.

Notice below that our test fails. The reason being, we are expecting status code 404 but received 200

Let us now test below api having response code of 404

Our code would look ike below

Save and execute. The test passes

Code snippet (keyress)

import​​ {test,expect}​​ from​​ '@playwright/test'

 

test("keypress",​​ async​​ ({​​ page​​ })​​ =>​​ {

   ​​ await​​ page.goto('https://the-internet.herokuapp.com/')

   ​​ 

   ​​ await​​ page.locator("text=Key Presses").click()

   ​​ await​​ page.press('#target','F1')

       ​​ 

   ​​ await​​ page.pause()    

})

 

Code snippet (api get request)

import​​ {test,expect}​​ from​​ '@playwright/test'

 

test("api get response",​​ async​​ ({​​ request​​ })​​ =>​​ {

   //const response =  await request.get('https://reqres.in/api/users/2')

   const​​ response​​ =  await​​ request.get('https://reqres.in/api/users/23')

 

   ​​ //expect(response.status()).toBe(200)  ​​ 

   ​​ expect(response.status()).toBe(404)  ​​ 

})

​​ 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 1st Nov 2024