Playwright API Testing Demo for Beginners

Поділитися
Вставка
  • Опубліковано 1 гру 2024
  • All Free Tutorials 🟢 AutomationStep...
    Project Setup
    Create a API Test Step-by-Step
    How to run a GET API Request
    How to run a POST API Request
    How to run a PUT API Request
    How to run a DELETE API Request
    How to validate API Response
    Check response, logs, errors in UI Mode
    Check HTML Report
    API Testing with Playwright - Project Setup
    Step 1 - Create a new folder for API Testing Project
    Step 2 - Open the folder in VS Code
    Step 3 - Open terminal on the location of the folder and run command npm init playwright@latest
    Step 4 - Check if demo tests are running fine using commands npx playwright test
    npx playwright test --ui
    npx playwright show-report
    Step 5 - Create a new file for API Tests (api-tests.spec.js)
    *How to run a GET API Request *
    Step 1 - Add imports
    import { test, expect } from '@playwright/test';
    Step 2 - Create a test using request context
    test.only('Demo API Test', async({request}) => { })
    Step 3 - Send a GET request & store response in a variable
    const response = await request.get('reqres.in/api/...)
    Step 4 - Verify the status code of the response is 200
    expect(response.status()).toBe(200);
    Step 5 - Check response contains some text
    const text = await response.text();
    expect(text).toContain('Janet');
    Step 6 - Write response on the console
    console.log(await response.json());
    Step 7 - Run and check results
    How to run a POST API Request
    Step 1 - Add imports
    import { test, expect } from '@playwright/test';
    Step 2 - Create a test using request context
    test.only('Demo API POST request’, async({request}) => {...})
    Step 3 - Send a POST request along with request body & store response in a variable
    const response = await request.post("reqres.in/api/...", {
    data: {
    "name": "Raghav",
    "job": "teacher"
    }
    })
    Step 4 - Verify response status code is 201
    expect(response.status()).toBe(201);
    Step 5 - Check response contains some text
    const text = await response.text();
    expect(text).toContain(Raghav);
    Step 6 - Write response on the console
    console.log(await response.json());
    Step 7 - Run and check results
    How to run a PUT API Request
    test('Demo API PUT Request', async ({ request }) => {
    const response = await request.put("reqres.in/api/...", {
    data: {
    "name": "Raghav",
    "job": "teacher"
    }
    })
    expect(response.status()).toBe(200);
    const text = await response.text();
    expect(text).toContain('Raghav');
    console.log(await response.json());
    })
    How to run a DELETE API Request
    test('Demo API DELETE Request', async ({ request }) => {
    const response = await request.delete("reqres.in/api/...")
    expect(response.status()).toBe(204);
    })
    References
    playwright.dev...
    playwright.dev...
    playwright.dev...
    playwright.dev...
    reqres.in/
    What is Package.json - • All you need to know a...
    ▬▬▬▬▬▬▬
    Every Like & Subscription gives me great motivation to keep working for you
    You can support my mission for education by sharing this knowledge and helping as many people as you can
    If my work has helped you, consider helping any animal near you, in any way you can
    Never Stop Learning
    Raghav Pal
    ▬▬▬▬ USEFUL LINKS ▬▬▬▬
    Ask Raghav - bit.ly/2CoJGWf
    Shorts Eng - bit.ly/3H9bifV
    Shorts Hindi - bit.ly/3XY7XqN
    GitHub Repositories - github.com/Rag...
    Udemy - automationstep...
    Stories - automationstep...
    -

КОМЕНТАРІ • 129

  • @KarthikJambagi
    @KarthikJambagi Рік тому +4

    You are the best example of the "Simplicity is the Best city". Thanks for this video.

  • @PoolMedia
    @PoolMedia Місяць тому +2

    Just finished the entire course, thank you so much!

    • @RaghavPal
      @RaghavPal  Місяць тому

      Thanks a lot.. keep learning

  • @KasuriThiyumini
    @KasuriThiyumini Рік тому +2

    Your UA-cam videos have been a lifeline for me in my studies, Sir . Thank you for being such an excellent teacher and sharing your expertise with the world.

    • @KasuriThiyumini
      @KasuriThiyumini Рік тому

      If possible, could you please advice on this sir, I was trying to execute the drop down menu option using the playwright. This is my code and unable to execute this--------- await page.locator("[id='#status']").selectOption({ label: 'Confirmed' });
      and these are the elements:

    • @RaghavPal
      @RaghavPal  Рік тому

      Most welcome Kasuri
      There are a few possible reasons why your Playwright code is not working to select the option "Confirmed" from the dropdown menu.
      First, make sure that the dropdown menu is visible and enabled before you try to select an option. You can do this by using the `page.waitForSelector()` method to wait for the dropdown menu element to become visible and enabled.
      Second, make sure that you are using the correct selector to locate the dropdown menu element. In your code, you are using the `#status` selector. However, the HTML code that you provided shows that the dropdown menu element has the `id="react-aria519914487-:r4m: react-aria519914487-:r4i:"` selector. You can try using this selector instead.
      Finally, make sure that you are using the correct method to select an option from the dropdown menu. In Playwright, you can use the `page.selectOption()` method to select an option from a dropdown menu. The `selectOption()` method takes two arguments: the selector for the dropdown menu element and the label of the option that you want to select.
      Here is an example of how to use the `page.selectOption()` method to select the option "Confirmed" from the dropdown menu:
      // Wait for the dropdown menu element to become visible and enabled.
      await page.waitForSelector('#react-aria519914487-:r4m: react-aria519914487-:r4i:', { state: 'visible' });
      // Select the option "Confirmed" from the dropdown menu.
      await page.selectOption('#react-aria519914487-:r4m: react-aria519914487-:r4i:', 'Confirmed');
      If you are still having trouble selecting the option "Confirmed" from the dropdown menu, you can try using the Playwright Inspector to inspect the dropdown menu element and to get more information about the element.
      I hope this helps

    • @KasuriThiyumini
      @KasuriThiyumini Рік тому

      Thanks a lot Sir, for the detail direction.

  • @alleluiaizimpamvu9971
    @alleluiaizimpamvu9971 10 місяців тому +2

    This channel is my second home, thank you for all your amazing tutorials

    • @RaghavPal
      @RaghavPal  10 місяців тому

      You're very welcome Alleluia. So happy & humbled to hear this

  • @TatevikPoghosyan-x3q
    @TatevikPoghosyan-x3q Рік тому +1

    Thanks for your lessons. You are the best teacher I ever met.

  • @petropolisful
    @petropolisful 4 місяці тому

    Just finished this series on Playwright. What a great introduction to the Playwright docs! Lots of helpful examples to get started with. You have a great presentation voice for this material, by the way. Thanks for the instructions and encouragement throughout this playlist!

    • @RaghavPal
      @RaghavPal  4 місяці тому

      Glad it was helpful Petros

  • @spudman2000
    @spudman2000 Рік тому +2

    Perfect timing Raghav, I've been going through your step by step guide on Playwright UI automation but I was also interested if Playwright can be used for API testing. Would be great if you could do a guide on data-driven API tests in Playwright too.

    • @RaghavPal
      @RaghavPal  Рік тому

      Glad it was helpful. Will plan for more lectures

    • @davisraj
      @davisraj Рік тому

      Yeah, I'd be interested too!

  • @СергейПилипенко-л1ъ
    @СергейПилипенко-л1ъ 5 місяців тому +6

    From Russia with love! :-) Dude, you have a talent for explaining complex topics in simple language. The best course on the Internet that I could find. I watched it in one breath. Keep it up!

    • @RaghavPal
      @RaghavPal  5 місяців тому

      Great to hear Сергей. Humbled

  • @jasonleelawlight
    @jasonleelawlight 24 дні тому

    Thank you for this awesome video series! I didn't know anything about Playwright before but I just went through all your videos very quickly, and now I feel ready for this testing tool. I'll certainly need some practice but I think I'll get a hang of it very soon.

    • @RaghavPal
      @RaghavPal  23 дні тому

      So glad to know this helped Jason.. keep learning

  • @ManojKumar-yw9cm
    @ManojKumar-yw9cm 7 місяців тому

    The whole course was amazing , thanks Raghav

    • @RaghavPal
      @RaghavPal  7 місяців тому

      Most welcome Manoj

  • @RohiTSingh-db4sv
    @RohiTSingh-db4sv 4 місяці тому

    Thanks Raghav for such a nice and quick session

    • @RaghavPal
      @RaghavPal  4 місяці тому

      Always welcome Rohit

  • @peterinvestor
    @peterinvestor 6 місяців тому

    Thanks for the course.
    I was already familiar with playwright but it was refreshing.
    However what I am missing is real life examples. How to structure tests and how to do them.
    I have a project where we have 20 user roles, 1000 different input fields / dropdowns.
    Based on what user will fill it will take different workflow.
    How can I somehow make sure that database is reloaded with same data after successful tests.
    How to read data from .csv file to use them in forms.
    How to repeat same tests but with different input values.
    How to make sure that tests are run in correct sequence instead of running each file separately.
    This is honestly good for start but bigger projects require more thoughts than just how to fill 2 input fields with same data over and over again and clicking on 1 button.
    Could you point me on such course please.

    • @RaghavPal
      @RaghavPal  6 місяців тому

      Glad to know it helped Peter. This course was for complete beginners to get started with Playwright. You can find many resources online to help you further with your Playwright learning journey. I have not searched and filtered any courses yet, but you can search online as per your needs and will find several options.
      All the best
      --

  • @ravirajug1137
    @ravirajug1137 9 місяців тому

    good one . cleanly explained about api testin.

    • @RaghavPal
      @RaghavPal  9 місяців тому

      Thanks for liking Raju

  • @skhambampati
    @skhambampati 4 місяці тому +1

    Hi Raghav- Thank you for taking time and doing .
    One question on get request. Since you are looking entire for Name. Is there a way to look for specific or first occurence of that name

    • @RaghavPal
      @RaghavPal  4 місяці тому

      Sravan
      Let's break down the problem step by step.
      Step 1: Understand the API Response
      Let's assume the API response is in JSON format. You can use Playwright's `response.json()` method to parse the response into a JSON object.
      Step 2: Identify the Path to the "Name" Element
      Examine the JSON object and identify the path to the "Name" element. For example, let's say the JSON object looks like this:
      ```json
      {
      "data": {
      "user": {
      "name": "John Doe",
      "address": {
      "name": "Home Address"
      }
      },
      "products": [
      {
      "name": "Product 1",
      "description": "This is product 1"
      },
      {
      "name": "Product 2",
      "description": "This is product 2"
      }
      ]
      }
      }
      ```
      In this example, there are three occurrences of the "Name" element:
      1. `data.user.name`
      2. `data.products[0].name`
      3. `data.products[1].name`
      Step 3: Use JSON Path or JavaScript to Extract the Desired "Name" Element
      To extract the specific or first occurrence of the "Name" element, you can use JSON Path or JavaScript.
      Option 1: Using JSON Path
      Playwright provides a `response.jsonPath()` method that allows you to extract data from the JSON response using JSON Path expressions. For example, to extract the first occurrence of "Name", you can use the following code:
      ```javascript
      const name = await response.jsonPath('$.data.user.name');
      ```
      This will extract the value of `data.user.name`, which is "John Doe".
      Option 2: Using JavaScript
      Alternatively, you can use JavaScript to traverse the JSON object and extract the desired "Name" element. For example, to extract the first occurrence of "Name", you can use the following code:
      ```javascript
      const jsonObject = await response.json();
      const name = jsonObject.data.user.name;
      ```
      This will also extract the value of `data.user.name`, which is "John Doe".
      Option 3: Using JavaScript with Array Methods
      If you want to extract all occurrences of "Name" or a specific occurrence, you can use JavaScript array methods. For example, to extract all occurrences of "Name", you can use the following code:
      ```javascript
      const jsonObject = await response.json();
      const names = [];
      Object.values(jsonObject).forEach((value) => {
      if (typeof value === 'object') {
      Object.values(value).forEach((innerValue) => {
      if (innerValue.name) {
      names.push(innerValue.name);
      }
      });
      }
      });
      console.log(names); // Output: ["John Doe", "Product 1", "Product 2"]
      ```
      This code will extract all occurrences of "Name" and store them in an array.

  • @infotech9196
    @infotech9196 6 місяців тому

    Want to thank you Sir for such an amazing tutorials and step by step guidelines.

    • @RaghavPal
      @RaghavPal  6 місяців тому +1

      You are most welcome Arsalan

  • @SakataSamig
    @SakataSamig Рік тому

    Thank you very much Raghav, very easy to follow tutorial, I have learned a lot. I have just begun my career in software testing, this is simply great stuff. Subscribed, never stop learning!

  • @ithihas
    @ithihas 3 місяці тому

    hi....do u have any video where we add necessary certs required for inhouse URLs for API testing...

    • @RaghavPal
      @RaghavPal  3 місяці тому +1

      No Ithihas, will need to check online examples

    • @ithihas
      @ithihas 3 місяці тому

      @@RaghavPal anyways thanks for the reply

  • @vedashreeravish8062
    @vedashreeravish8062 3 місяці тому

    Hi Raghav, this the best video I have found on internet for API Framework development..
    can you please help with new set of videos for API auth and other topics (End-to-End) API framework..thanks a lot for this knowledge transfer 😊

    • @RaghavPal
      @RaghavPal  3 місяці тому

      Glad to do this Veda. Can check more here - automationstepbystep.com/

  • @saikrishnacheekoti
    @saikrishnacheekoti Рік тому

    Hi Raghav, Your explanation on Playwright Automation is top-notch. It is helping me a lot in understanding what a Playwright is ?. I want to continue learning more about Playwright features like Component testing. Could you please do videos on component testing using Playwright?

    • @RaghavPal
      @RaghavPal  Рік тому +1

      Glad to know this Krishna
      I will plan on this

  • @terjemahanminda-ahmadfahmi6343
    @terjemahanminda-ahmadfahmi6343 6 місяців тому

    Hi Raghav, if we use playwright-maestro for functional test, and vitest for backend unit test; what tool would you suggest for our test management tools?

    • @RaghavPal
      @RaghavPal  6 місяців тому

      Terjemahan
      When it comes to test management tools, there are several options available, each with its own strengths and features. Let's explore a few popular ones:
      1. TestRail:
      - Description: TestRail is a web-based test case management tool that allows you to organize, track, and manage your test cases and test runs.
      - Features:
      - Test case organization: Create test suites, test cases, and test plans.
      - Execution tracking: Record test results and link them to specific test cases.
      - Reporting: Generate detailed reports and metrics.
      - Integration: Integrates with various test automation tools.
      - Pros: User-friendly interface, good reporting capabilities, and integrations.
      - Cons: Requires a license (not free).
      2. Zephyr:
      - Description: Zephyr is a popular test management solution for Jira.
      - Features:
      - Seamless integration with Jira: Manage test cases directly within Jira.
      - Test execution tracking: Execute tests and track results.
      - Customization: Create custom fields and workflows.
      - Traceability: Link test cases to requirements and defects.
      - Pros: Jira integration, flexibility, and scalability.
      - Cons: Requires a Jira license.
      3. qTest:
      - Description: qTest is a cloud-based test management tool.
      - Features:
      - Test case management: Organize test cases, test cycles, and test runs.
      - Collaboration: Allows teams to collaborate on testing.
      - Integration: Integrates with various test automation tools.
      - Reporting: Provides detailed reports.
      - Pros: Cloud-based, good collaboration features.
      - Cons: Pricing may be a concern for some teams.
      4. Xray:
      - Description: Xray is an add-on for Jira that focuses on test management.
      - Features:
      - Test case management: Create, organize, and execute test cases.
      - BDD support: Integrates with Cucumber and other BDD frameworks.
      - Traceability: Links test cases to requirements and defects.
      - Reporting: Provides customizable reports.
      - Pros: Jira integration, BDD support.
      - Cons: Requires a Jira license.
      5. Kiwi TCMS:
      - Description: Kiwi TCMS is an open-source test case management system.
      - Features:
      - Test case organization: Create test plans, test cases, and test runs.
      - Execution tracking: Record test results.
      - Integration: Integrates with various tools.
      - Customization: Open-source and customizable.
      - Pros: Free and open-source, customizable.
      - Cons: May require more setup and maintenance.
      Remember that the best choice depends on your team's specific needs, budget, and existing toolset. Consider factors such as integration with your existing tools, ease of use, scalability, and reporting capabilities. Evaluate a few options and choose the one that aligns best with your team's requirements

  • @Mr47CRO
    @Mr47CRO 8 місяців тому

    Raghav, I have completed your playwright beginner tutorial and I must say thank you from the bottom of my heart. You are an amazing human being & teacher!
    Can I ask you one question, is the knowledge from this course enough to land a junior position as a playwright automation tester?

    • @RaghavPal
      @RaghavPal  8 місяців тому +1

      You're very welcome James
      Yes, if you have followed with hands-on it will definitely help you to get the job..

  • @nguyenxuanhoan9448
    @nguyenxuanhoan9448 5 місяців тому +1

    I wanna maximine chromium when I run test. Can u share it ??

    • @RaghavPal
      @RaghavPal  5 місяців тому

      Nguyễn
      Let's break down the problem step by step.
      Step 1: Import Playwright
      First, make sure you have imported Playwright in your JavaScript file:
      ```javascript
      const playwright = require('playwright');
      ```
      Step 2: Launch Chromium
      Next, launch a new instance of Chromium using Playwright:
      ```javascript
      (async () => {
      const browser = await playwright.chromium.launch();
      //...
      })();
      ```
      Step 3: Create a new context
      Create a new browser context, which will allow you to create a new page:
      ```javascript
      const context = await browser.newContext();
      ```
      Step 4: Create a new page
      Create a new page within the context:
      ```javascript
      const page = await context.newPage();
      ```
      Step 5: Maximize the browser window
      Now, maximize the browser window using the `viewport` method:
      ```javascript
      await page.setViewportSize({ width: 1920, height: 1080 });
      ```
      In this example, we're setting the viewport size to 1920x1080, which will maximize the browser window. You can adjust these values to fit your specific needs.
      Putting it all together
      Here's the complete code:
      ```javascript
      const playwright = require('playwright');
      (async () => {
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.setViewportSize({ width: 1920, height: 1080 });
      // Your test code goes here...
      await browser.close();
      })();
      ```
      Run this code, and Playwright should launch Chromium, create a new page, and maximize the browser window to the specified size. Then, you can write your test code to interact with the page
      -

  • @terjemahanminda-ahmadfahmi6343
    @terjemahanminda-ahmadfahmi6343 7 місяців тому +1

    Hi Raghav, have you tried Maestro? I'm looking for automated testing tool for single code base react native application. right now, Playwright is looked can help to perform test for web & API. but for maestro, it also can perform test on webview. Do you have any comments on this comparisons?

    • @RaghavPal
      @RaghavPal  7 місяців тому

      Terjemahan
      When it comes to automated testing for React Native applications, there are several tools available
      1. **Jest**: Ideal for unit and component testing in React Native.
      2. **Appium**: Cross-platform choice for E2E testing.
      3. **Detox**: Specifically designed for comprehensive E2E testing in React Native.
      4. **Karma** and **Jasmine**: Good for unit and integration testing, but not React Native-specific.

    • @terjemahanminda-ahmadfahmi6343
      @terjemahanminda-ahmadfahmi6343 7 місяців тому

      @@RaghavPal tq for the info. My next question is, is the comparison of playwright & maestro is apple to apple?

    • @RaghavPal
      @RaghavPal  7 місяців тому +1

      Playwright is a versatile tool for cross-browser testing and web automation, while Maestro is specialized for mobile app testing. Choose the tool that aligns best with your specific testing needs and the platforms you’re targeting

    • @terjemahanminda-ahmadfahmi6343
      @terjemahanminda-ahmadfahmi6343 7 місяців тому

      @@RaghavPal tq for the answer.

  • @umesh1056
    @umesh1056 Рік тому

    Hi Raghav , Do you have videos or link about the below scenarios
    1.Generate a auth token
    2.Use the token generated in step 1 and utilize in all the scripts so that we dont need to generate a token for each scripts

    • @RaghavPal
      @RaghavPal  Рік тому

      Umesh
      not specifically on Playwright yet

  • @parasharp28
    @parasharp28 4 місяці тому

    Raghav, can I use the APIs to create users first and then run the automated functional tests with the users that got created via API, in single go

    • @RaghavPal
      @RaghavPal  4 місяці тому

      Pranav
      Let's break down the problem step by step.
      Step 1: Understand the requirement
      You want to use Postman to create users via APIs and then run automated functional tests using those created users in a single go.
      Step 2: Identify the components involved
      * Postman: a popular API testing tool
      * APIs: Application Programming Interfaces to create users
      * Automated functional tests: tests that verify the functionality of the application using the created users
      Step 3: Determine the feasibility
      Yes, it is possible to create users via APIs using Postman and then run automated functional tests using those created users in a single go.
      Step 4: Outline the approach
      Here's a high-level outline of the approach:
      a. Create a Postman collection with the following requests:
      * API request to create a user (e.g., `POST /users`)
      * API request to retrieve the created user's details (e.g., `GET /users/{userId}`)
      b. Use Postman's built-in features to store the created user's details in a variable (e.g., `userId`, `username`, `password`)
      c. Create a separate Postman collection or folder for the automated functional tests
      d. In the automated functional tests, use the stored variables from step b to authenticate and test the application's functionality
      Step 5: Implement the solution
      Here's a more detailed implementation plan:
      a. Create a new Postman collection, e.g., "User Creation"
      b. Add a `POST /users` request to create a new user, with the required payload (e.g., `username`, `password`, `email`)
      c. Add a `GET /users/{userId}` request to retrieve the created user's details
      d. Use Postman's `Tests` tab to store the created user's details in variables, e.g.:
      ```json
      pm.variables.set("userId", pm.response.json().id);
      pm.variables.set("username", pm.response.json().username);
      pm.variables.set("password", pm.response.json().password);
      ```
      e. Create a new Postman collection or folder, e.g., "Automated Functional Tests"
      f. Add test requests to this collection that use the stored variables to authenticate and test the application's functionality, e.g.:
      ```json
      {{baseUrl}}/login
      - Headers:
      - Authorization: Basic {{username}}:{{password}}
      - Body:
      - username: {{username}}
      - password: {{password}}
      ```
      g. Run the "User Creation" collection first, followed by the "Automated Functional Tests" collection
      By following these steps, you should be able to create users via APIs using Postman and then run automated functional tests using those created users in a single go
      -

  • @0megaFive
    @0megaFive 8 місяців тому

    Your videos are amazing.
    I have an issue.
    I'm reading emails from an email server using the API.
    But I run into the issue of there's 2 emails, and each email has a different subject.
    Can I parse the json into some type of array so that I can grab the information on the email with the subject I want.

    • @RaghavPal
      @RaghavPal  8 місяців тому

      Mike
      To handle the JSON response from your email server API and extract the relevant information based on the email subject, you can follow these steps:
      1. Parse the JSON Response:
      - First, parse the JSON response you receive from the API. You can use `JSON.parse(response)` in JavaScript to convert the JSON string into a JavaScript object.
      - Make sure that the response is a valid JSON string. If it's not, you might need to address any formatting issues.
      2. Identify the Email with the Desired Subject:
      - Once you have the parsed object, iterate through the emails (which are likely represented as an array of objects).
      - Check each email's subject to find the one you're interested in.
      3. Create an Array for Filtered Emails:
      - Initialize an empty array (let's call it `filteredEmails`).
      - As you iterate through the emails, if an email matches the desired subject, push it into the `filteredEmails` array.
      4. Process the Filtered Emails:
      - Now you have an array containing only the emails with the subject you want.
      - You can loop through this array and process each email as needed (e.g., extract specific fields, perform actions, etc.).
      Here's a simplified example of how you might achieve this in JavaScript:
      ```javascript
      // Assume your API response looks like this (an array of email objects):
      const apiResponse = [
      {
      id: 1,
      subject: 'Important Meeting',
      // Other email properties...
      },
      {
      id: 2,
      subject: 'Confirmation: Event Registration',
      // Other email properties...
      },
      // More emails...
      ];
      // Desired subject (you can replace this with your actual subject):
      const desiredSubject = 'Important Meeting';
      // Initialize an array to store filtered emails:
      const filteredEmails = [];
      // Parse the API response (assuming it's a valid JSON string):
      try {
      const emails = JSON.parse(apiResponse);
      // Filter emails based on the desired subject:
      emails.forEach((email) => {
      if (email.subject === desiredSubject) {
      filteredEmails.push(email);
      }
      });
      // Now you can process the filtered emails:
      filteredEmails.forEach((filteredEmail) => {
      // Extract relevant information from each email (e.g., sender, timestamp, etc.)
      console.log(filteredEmail);
      });
      } catch (error) {
      console.error('Error parsing API response:', error);
      }
      ```
      Remember to adapt this code to your specific use case, including handling any additional email properties and adjusting the filtering logic based on your subject criteria

  • @michaeledmondson6193
    @michaeledmondson6193 Рік тому +1

    This video is perfect but will you also make one about creating classes for data to feed into the UI test? i feel like this was a really important topic that was missed for this. Also will you make the same video for Selenium Python as far as Data and api testing?

  • @pallavisr9416
    @pallavisr9416 10 місяців тому

    Thanks .. :) it was awesome.. ty again :) God bless you

    • @RaghavPal
      @RaghavPal  9 місяців тому

      You are so welcome Pallavi

  • @PraveenKumar-m5h5p
    @PraveenKumar-m5h5p 8 місяців тому

    Hi Raghav, Can you suggest how print console log of request that I am sending? I need it for debugging. I tried different options couldn't succeed in playwright. Thanks

    • @RaghavPal
      @RaghavPal  8 місяців тому

      Praveen
      you can use the `page.on('request')` event to log all network requests. Here's a simple example:
      ```javascript
      const playwright = require('playwright');
      (async () => {
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      // Log and print all network requests
      page.on('request', request => {
      console.log(`Request made: ${request.url()}`);
      });
      await page.goto('example.com');
      await browser.close();
      })();
      ```
      In this example, every time a network request is made, the URL of the request will be logged to the console. This should help you debug the network activity of your Playwright script. Remember to replace `'example.com'` with the URL you want to navigate to.

  • @samyourwell-wisher7008
    @samyourwell-wisher7008 Рік тому

    Hi sir ji in my org we cant run the chrome installed on playwright,same thing with edge and firefox, please tell me how can we overcome this,can we commant playwright to launch browser from locally installed location???

    • @RaghavPal
      @RaghavPal  Рік тому

      Sam
      Yes, Playwright can be configured to launch browsers from locally installed locations. To do this, you can set the `executablePath` property when creating a browser instance. For example, to launch Chrome from a local installation at `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`, you would use the following code:
      ```javascript
      const browser = await chromium.launch({
      executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
      });
      ```
      You can also use environment variables to specify the paths to the browser executables. For example, you could set the following environment variables:
      ```
      PLAYWRIGHT_CHROMIUM_BIN=/Applications/Google Chrome.app/Contents/MacOS/Google Chrome
      PLAYWRIGHT_EDGE_BIN=/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge
      PLAYWRIGHT_FIREFOX_BIN=/Applications/Firefox.app/Contents/MacOS/firefox
      ```
      Once you have set the environment variables, Playwright will automatically use the local installations of Chrome, Edge, and Firefox when you launch them.
      Here is an example of how to use the environment variables to launch a Chromium browser:
      ```javascript
      const browser = await chromium.launch();
      ```
      Playwright will automatically use the browser executable specified by the `PLAYWRIGHT_CHROMIUM_BIN` environment variable.
      I hope this helps

  • @DeeplaxmiKulkarni-ce7wm
    @DeeplaxmiKulkarni-ce7wm 6 місяців тому

    Getting error: apiRequestcontext.get: self-signed certificate in certificate chain. Please help to resolve this

    • @RaghavPal
      @RaghavPal  6 місяців тому +1

      Deeplaxmi
      The "self-signed certificate in certificate chain" error typically occurs when Playwright encounters an untrusted certificate authority (CA) during the API request. Let's explore some solutions to resolve this issue:
      1. Trust Custom Root Certificates:
      - If your company intercepts traffic and uses a custom CA certificate, you'll need to trust it on the OS level. This allows Node.js (which Playwright relies on) to recognize the certificate.
      - Set the `NODE_EXTRA_CA_CERTS` environment variable to point to your custom root certificate file. For example, if your certificate is located at `C:\certs
      oot.crt`, run the following command before running your Playwright tests:
      ```
      $Env:NODE_EXTRA_CA_CERTS="C:\certs
      oot.crt"
      node your_test_script.js
      ```
      - Alternatively, you can configure Playwright to use the custom certificate directly in each request. For instance:
      ```javascript
      const opts = {
      method: 'GET',
      hostname: 'localhost',
      port: 443, // Adjust the port as needed
      path: '/',
      ca: fs.readFileSync('path/to/cacert.pem'), // Path to your custom CA certificate
      };
      https.request(opts, (response) => {
      // Handle the response
      }).end();
      ```
      2. Disable SSL Verification (Not Recommended for Production):
      - In development environments, you can temporarily disable SSL verification. However, this is not recommended for production.
      - Set the `NODE_TLS_REJECT_UNAUTHORIZED` environment variable to `0`:
      ```
      export NODE_TLS_REJECT_UNAUTHORIZED=0
      node your_test_script.js
      ```
      - Alternatively, configure npm to use a specific certificate file:
      ```
      npm config set cafile path/to/cacert.pem
      ```
      3. Use a Proper SSL Certificate:
      - For production environments, consider obtaining a proper SSL certificate from a trusted source (e.g., Let's Encrypt). This ensures secure communication without encountering self-signed certificate issues.
      Remember that while disabling SSL verification might be convenient during development, it poses security risks in production. Always use trusted certificates for secure communication
      For more information, you can refer to the Playwright documentation on [browsers and proxies](playwright.dev/docs/browsers)
      --

    • @DeeplaxmiKulkarni-ce7wm
      @DeeplaxmiKulkarni-ce7wm 6 місяців тому

      I will try the given option, if it didn’t work can we connect and I will show you exactly what is happning

    • @RaghavPal
      @RaghavPal  6 місяців тому

      Yes, please try, and can also check some online examples

  • @davisraj
    @davisraj Рік тому

    Is there a specific reason/benefit of using Javascript vs Typescript?

    • @RaghavPal
      @RaghavPal  Рік тому

      Davis
      Yes, there are specific reasons and benefits to using JavaScript and TypeScript with Playwright, each with its own advantages and disadvantages.
      JavaScript:
      Benefits:
      * Widely used: JavaScript is a popular language with a large community and extensive resources available, making it easier to find solutions and support.
      * Simpler syntax: JavaScript has a relatively simpler syntax compared to TypeScript, making it easier to learn and use for beginners.
      * Dynamic typing: JavaScript offers dynamic typing, which can be helpful for rapid prototyping and scripting tasks.
      Disadvantages:
      * Error-prone: JavaScript's dynamic typing can lead to runtime errors that might be missed during development.
      * Limited type safety: JavaScript does not enforce type annotations, making it prone to type-related errors and inconsistencies.
      * Larger codebases: Lack of static typing may require more extensive unit testing and documentation for complex projects.
      TypeScript:
      Benefits:
      * Static type checking: TypeScript provides static typing, which catches type errors early in the development process, leading to more robust and reliable code.
      * Improved code maintainability: TypeScript's type annotations make code easier to read, understand, and maintain, especially for large projects.
      * Increased developer productivity: TypeScript's strong typing reduces debugging time and improves developer productivity.
      Disadvantages:
      * Increased complexity: TypeScript's additional features add a layer of complexity compared to using plain JavaScript.
      * Learning curve: TypeScript requires additional learning and may be less familiar to those less experienced with typed languages.
      * Compile-time overhead: TypeScript needs to be compiled to JavaScript before execution, adding an extra step to the development process.
      Ultimately, the choice between JavaScript and TypeScript for Playwright depends on your specific needs and preferences. Here's a general guideline:
      * Use JavaScript:
      * If you have a smaller, simpler project.
      * If you are comfortable with dynamic typing and confident in your ability to prevent errors.
      * If you value a simpler workflow and prioritize rapid prototyping.
      * Use TypeScript:
      * If you have a larger, complex project requiring robust code.
      * If you prioritize type safety and want to avoid runtime type errors.
      * If you value code maintainability and collaboration within a team.
      Remember that Playwright supports both JavaScript and TypeScript seamlessly, so you can try both and see which works best for your project and needs.

  • @sanjeev8720
    @sanjeev8720 9 місяців тому

    Hello sir.. can you please tell me how to work with api when we have bearer token for the same scenarios

    • @RaghavPal
      @RaghavPal  9 місяців тому

      Sanjeev
      Absolutely! Here's how you can work with APIs using bearer tokens in Playwright:
      1. Configuration:
      Environment Variable: Store your bearer token securely in an environment variable. Avoid hardcoding it in your tests for security reasons.
      Playwright Config (Optional): You can configure Playwright to automatically add the bearer token to all requests by setting the `extraHTTPHeaders` property in your `playwright.config.js` file like this:
      ```javascript
      module.exports = {
      use: {
      baseURL: 'your-api.com',
      extraHTTPHeaders: {
      Authorization: `Bearer ${process.env.API_TOKEN}`,
      },
      },
      };
      ```
      2. Making API Calls:
      `request` fixture: Playwright provides the `request` fixture in your test files for making API calls. You can access the current `APIRequestContext` and use its methods for different HTTP requests.
      Example (GET request):
      ```javascript
      test('Get user data', async ({ request }) => {
      const response = await request.get('/users/123');
      const data = await response.json();
      expect(data.name).toBe('John Doe');
      });
      ```
      Customize Headers: If needed, you can override the configured `Authorization` header for specific requests by adding it to the `headers` option:
      ```javascript
      const response = await request.post('/orders', {
      headers: {
      Authorization: `Bearer ${customToken}`,
      },
      });
      ```
      3. Advanced Techniques:
      Authentication Flow: If your API requires a separate login step to obtain the bearer token, you can use Playwright to automate the login process and store the token for subsequent requests.
      Dynamic Tokens: If your token expires or needs refreshing, you can implement logic to obtain a new token and update the headers accordingly.
      API Testing Suite: Consider building a suite of tests specifically for your API using Playwright, covering various scenarios and edge cases.

  • @shilpareddy2903
    @shilpareddy2903 Рік тому

    Hi sir, i done a post request and able to see bearer token in the output (console). How to get that token and pass it to next post , get request s

    • @RaghavPal
      @RaghavPal  Рік тому

      Shilpa
      There are several ways to extract the bearer token from the output of your Playwright-powered API test and pass it to subsequent requests:
      **1. Using regular expressions:**
      You can use regular expressions to search the console output for the bearer token pattern. Most tokens follow the format `Bearer [token_string]`. Here's an example with Python:
      ```python
      import re
      # Get console output
      console = page.context.tracing.start()
      await page.goto("...") # Your API request
      tracing = await console.stop()
      # Extract token using regex
      pattern = r"Bearer ([\w\d\-]+)"
      match = re.search(pattern, tracing.text)
      # Check if token was found
      if match:
      bearer_token = match.group(1)
      print(f"Extracted bearer token: {bearer_token}")
      else:
      print("Bearer token not found in console output")
      # Use token in subsequent requests
      headers = {"Authorization": f"Bearer {bearer_token}"}
      await page.goto("...", headers=headers) # Subsequent API request
      ```
      **2. Using Playwright's network interception:**
      Playwright allows you to intercept and inspect network requests and responses. You can intercept the response from your initial POST request and retrieve the bearer token from the response headers. Here's an example:
      ```python
      from playwright.chromium import playwright
      async def extract_token(request):
      response = await request.fetch()
      headers = response.headers()
      if "Authorization" in headers:
      token = headers["Authorization"].split()[1]
      print(f"Extracted bearer token: {token}")
      return token
      else:
      print("Bearer token not found in response headers")
      return None
      async def main():
      browser = await playwright.chromium.launch()
      context = await browser.new_context()
      await context.route(url="...", handler=extract_token)
      await page.goto("...") # Your API request
      # Use token in subsequent requests
      token = await extract_token(context.new_request("GET", "..."))
      if token:
      headers = {"Authorization": f"Bearer {token}"}
      await page.goto("...", headers=headers) # Subsequent API request
      await browser.close()
      if __name__ == "__main__":
      asyncio.run(main())
      ```
      **3. Using Playwright's storage API:**
      If the bearer token is stored in browser storage after the initial request, you can use Playwright's storage API to access it and use it in subsequent requests. This approach might be suitable if the token persists for the entire session.
      Choose the method that best fits your needs and the structure of your API responses. Remember to adapt the code snippets to your specific API endpoints and token format.

  • @seranKumar-r9c
    @seranKumar-r9c 5 місяців тому

    Hi sir, i was recently seen u r videos and learning the API testing and i have small doubt is there once i done the terminal but not showing the java script level its showing error that's means '' npm init playwright@latest'' getting error, so please give me the result asap.

    • @RaghavPal
      @RaghavPal  5 місяців тому

      Seran
      Here are a few steps you can follow to resolve the error:
      1. Permissions Issue:
      - First, ensure that you have the necessary permissions to create files and directories in the location where you're running the command.
      - If you're in a system folder (e.g., `C:\\Program Files\
      odejs`), try running the command as an administrator. Open your terminal as an administrator and then execute `npm init playwright@latest`.
      2. Clean Up Existing Files:
      - Delete the `node_modules` folder and the `package-lock.json` file if they exist in your project directory.
      - Then, rerun the command: `npm init playwright@latest`.
      3. Retry the Installation:
      - After cleaning up, try running the initialization command again: `npm init playwright@latest`.
      - This time, everything should be installed correctly.
      Remember to follow these steps, and hopefully, you'll be able to create your Playwright project successfully
      -

  • @priyankav2890
    @priyankav2890 7 місяців тому

    You are the best !thank you so much Raghav for this.
    I understood the basics of api testing
    Can you please let me know on how to do deep dive into more like what kind of advanced topics I should explore in api testing

    • @RaghavPal
      @RaghavPal  7 місяців тому +1

      Priyanka
      Certainly! Once you've grasped the basics of API testing, diving into advanced topics will enhance your skills and make you a more effective API tester. Here are some areas to explore:
      1. API Test Data Management:
      - Managing test data is crucial for API testing. Explore techniques for creating dynamic test data, handling different data formats (JSON, XML), and ensuring data consistency across test runs
      2. Automated Testing of Webhooks and Callbacks:
      - Webhooks and callbacks are essential for real-time communication between systems. Learn how to test APIs that rely on webhooks and handle asynchronous events².
      3. API Chaining and Composite Tests:
      - APIs often interact with each other. Practice chaining multiple API calls together (e.g., extracting data from one API response and using it in another request).
      - Composite tests involve testing multiple APIs as part of an end-to-end scenario.
      4. Handling Asynchronous API Calls:
      - Some APIs return responses asynchronously (e.g., long-running processes). Understand techniques for waiting, polling, and handling timeouts in such cases².
      5. Security Testing:
      - Dive deeper into API security testing:
      - Authentication and Authorization: Explore different authentication methods (OAuth, API keys, JWT) and test their implementation.
      - Input Validation: Test for SQL injection, XSS, and other security vulnerabilities.
      - Rate Limiting and Throttling: Verify that rate limits are enforced correctly.
      - Sensitive Data Exposure: Ensure that sensitive data (such as passwords or tokens) is not exposed in API responses.
      6. Performance and Load Testing:
      - Use tools like JMeter or Gatling to simulate heavy loads and measure API performance.
      - Explore techniques for identifying bottlenecks and optimizing API response times.
      7. Contract Testing:
      - Contract testing ensures that APIs adhere to their defined contracts (e.g., OpenAPI specifications). Learn about tools like Pact or Spring Cloud Contract.
      8. Exploratory Testing:
      - Go beyond scripted tests. Explore the API manually, try different inputs, and observe behavior.
      - Use tools like Postman or REST clients for exploratory testing.
      9. Versioning and Backward Compatibility:
      - Understand how to handle API versioning. Test backward compatibility to ensure that changes don't break existing clients³.
      10. API Documentation Testing:
      - Verify that API documentation (Swagger, OpenAPI) accurately reflects the API behavior.
      - Check if examples, parameters, and response schemas match the actual implementation.
      11. Boundary Testing and Negative Testing:
      - Test edge cases, invalid inputs, and unexpected scenarios.
      - Explore boundary values (minimum, maximum) for numeric inputs.
      12. Monitoring and Metrics:
      - Learn about monitoring tools (Prometheus, Grafana) to track API performance, error rates, and latency.
      - Understand key metrics (response time, throughput, error codes).
      Remember that practice is essential. Apply these concepts to real-world APIs, work on projects, and collaborate with developers. Happy exploring

    • @priyankav2890
      @priyankav2890 7 місяців тому

      @@RaghavPal thank you so much for the wonderful suggestions

  • @sivaramakrishnareddyrajula9605

    Hi, Do you have any video on authentication and authorization for API requests?

  • @michaeledmondson-f7q
    @michaeledmondson-f7q Рік тому

    Hey Raghav in real life scenarios where will i put my api key? most companies require you to test through a gateway is there any documentation you can point me to for that ?

    • @RaghavPal
      @RaghavPal  Рік тому

      Michael
      There are a few different places where you can put your API key in Playwright:
      *In the environment variables:* You can set the `PLAYWRIGHT_API_KEY` environment variable to your API key. Playwright will automatically read this environment variable when it starts up.
      *In the Playwright configuration file:* You can add the `apiKey` property to the `playwrightConfig` object in your Playwright configuration file.
      *In your test code:* You can pass your API key to the `page.setExtraHTTPHeaders()` method.
      Which method you choose depends on your specific needs. If you need to use your API key in multiple tests, it is recommended to set the `PLAYWRIGHT_API_KEY` environment variable or add the `apiKey` property to your Playwright configuration file. This will ensure that your API key is available to all of your tests without having to pass it in explicitly.
      If you need to use different API keys in different tests, or if you need to dynamically set the API key based on the test context, then you can pass the API key to the `page.setExtraHTTPHeaders()` method in your test code.
      Here is an example of how to set your API key in the environment variables:
      ```
      export PLAYWRIGHT_API_KEY="YOUR_API_KEY"
      ```
      Here is an example of how to set your API key in the Playwright configuration file:
      ```
      {
      "playwrightConfig": {
      "apiKey": "YOUR_API_KEY"
      }
      }
      ```
      Here is an example of how to set your API key in your test code:
      ```
      const page = await browser.newPage();
      await page.setExtraHTTPHeaders({
      "Authorization": "Bearer YOUR_API_KEY"
      });
      ```
      Most companies that require you to test through a gateway will have documentation on how to do so. However, there is no general documentation for this, as the approach will vary depending on the specific gateway.
      Here are some tips for finding documentation on testing through a gateway:
      * Check the company's website for documentation on their API and testing environment.
      * Search for the company's name and "API testing" online.
      * Contact the company's support team for assistance.
      I hope this helps

  • @LokeshAvula-c5p
    @LokeshAvula-c5p Рік тому

    how can we check for negative flow tests in API testing

    • @RaghavPal
      @RaghavPal  Рік тому

      Lokesh
      Here are some key strategies for checking for negative flow tests in API testing using Playwright:
      1. *Invalid Request Parameters:*
      - Send requests with missing, invalid, or excessive parameters to verify that the API validates input data correctly and returns appropriate error messages for invalid parameters.
      2. *Invalid Request Headers:*
      - Modify request headers with incorrect values or omit essential headers to test the API's resilience to invalid header information.
      3. *Unauthorized Requests:*
      - Make requests without providing authentication credentials or with invalid credentials to verify that the API enforces proper access control and returns unauthorized error responses for unauthorized access attempts.
      4. *Invalid Request Body:*
      - Send requests with invalid JSON structures, missing mandatory fields, or incorrect data types to test the API's ability to handle invalid request bodies.
      5. *Invalid HTTP Methods:*
      - Use the wrong HTTP method (e.g., GET instead of POST) for certain API endpoints to check that the API enforces proper HTTP method restrictions and returns appropriate error responses.
      6. *Non-Existent Resources:*
      - Send requests to non-existent endpoints or resources to verify that the API handles invalid resource requests gracefully and returns appropriate error responses indicating the resource's non-existence.
      7. *Resource Conflict or Overlapping Requests:*
      - Create resource conflicts or overlapping requests to test the API's ability to handle these situations appropriately and return appropriate error responses.
      8. *Excessive Load or Request Throttling:*
      - Send a high volume of requests or exceed request limits to test the API's performance under load and its ability to handle throttling or rate limiting mechanisms.
      9. *Invalid or Unexpected Content-Types:*
      - Send requests with incorrect or unexpected Content-Types to verify that the API validates content type information and returns appropriate error responses for invalid content types.
      10. *Invalid or Unexpected HTTP Status Codes:*
      - Send requests that intentionally trigger invalid or unexpected HTTP status codes to ensure that the API handles these situations gracefully and returns appropriate error responses.
      By implementing these strategies and carefully designing negative flow test cases, you can effectively test the robustness and error handling capabilities of your API endpoints using Playwright, ensuring that your API is resilient to unexpected or invalid requests.

  • @puvvusvlogs
    @puvvusvlogs 4 місяці тому

    Hi, can we use playwright to automate rest api's without a UI?

    • @RaghavPal
      @RaghavPal  4 місяці тому

      Yes you can, pls check playwright.dev/docs/api-testing

  • @Gamertyro
    @Gamertyro Рік тому +1

    sir plagly api use karke dikha do please ya fir or koi api jo plagrism check karee

    • @RaghavPal
      @RaghavPal  Рік тому +1

      I will check on this

    • @Gamertyro
      @Gamertyro Рік тому

      @@RaghavPal thanks 🙏🙏

  • @vasanthagajaraj1997
    @vasanthagajaraj1997 8 місяців тому

    Hi Raghav,
    Good Day!!
    Its value added videos for us to start with Playwright.
    Can you please add validating xml request and xml response API Testing in Playwright VSCode.
    Awaiting for your response!!
    Thanks!!

  • @techysam-bl9mk
    @techysam-bl9mk Рік тому

    Very beautifully explained

  • @michaeledmondson6193
    @michaeledmondson6193 Рік тому

    Hey Raghav where do i set up the api key or bearer token do you have any documentation on that?

    • @RaghavPal
      @RaghavPal  Рік тому

      Michael
      To set up the API key or bearer token in Playwright API testing, you can follow these steps:
      1. Create a new Playwright test file.
      2. Add the following code to the top of the test file:
      ```javascript
      import { test as setup } from '@playwright/test';
      setup('authenticate', async ({ request }) => {
      // Send authentication request. Replace with your own.
      await request.post('api.example.com/login', {
      form: {
      'username': 'user',
      'password': 'password',
      },
      });
      // Store the API key or bearer token in a global variable.
      global.apiKey = await request.storageState();
      });
      ```
      3. In your test cases, you can then use the `global.apiKey` variable to authenticate your requests. For example:
      ```javascript
      test('should make a successful API call', async ({ page }) => {
      // Set the authorization header with the API key or bearer token.
      page.setExtraHTTPHeaders({
      'Authorization': `Bearer ${global.apiKey}`,
      });
      // Make the API call.
      const response = await page.get('api.example.com/users');
      // Assert that the response was successful.
      expect(response.status()).toBe(200);
      });
      ```
      You can also set up the API key or bearer token in the Playwright configuration file. To do this, add the following code to the `playwright.config.ts` file:
      ```typescript
      import { defineConfig } from '@playwright/test';
      export default defineConfig({
      use: {
      // Set the authorization header for all requests.
      extraHTTPHeaders: {
      'Authorization': `Bearer ${process.env.API_KEY}`,
      },
      },
      });
      ```
      Then, in your test cases, you can use the `process.env.API_KEY` environment variable to authenticate your requests. For example:
      ```typescript
      test('should make a successful API call', async ({ page }) => {
      // Make the API call.
      const response = await page.get('api.example.com/users');
      // Assert that the response was successful.
      expect(response.status()).toBe(200);
      });
      ```
      Which method you choose to set up the API key or bearer token will depend on your specific needs and preferences.
      Here is a link to the official Playwright documentation on authentication: playwright.dev/docs/auth

  • @sonali420
    @sonali420 10 місяців тому

    do we have any more video apart from demo in playwright api testing

    • @RaghavPal
      @RaghavPal  10 місяців тому

      Sonali
      I believe for this Playlist, this is the last for now. Can check more here - automationstepbystep.com/

  • @softwaretestinglearninghub
    @softwaretestinglearninghub Рік тому

    this is very helpful, thank you!

  • @ThinhTran-i7h
    @ThinhTran-i7h 9 місяців тому

    do you think mac or window when doing testing?

    • @RaghavPal
      @RaghavPal  9 місяців тому

      Thinh
      did not get you exactly..

  • @nothingburger7
    @nothingburger7 Рік тому

    Hi Raghav, thanks for your perfect videos. By the way how do you think is it good idea to learn Python for automation?

    • @RaghavPal
      @RaghavPal  Рік тому

      Yes, I think it is a good idea to learn Python for automation. Python is a general-purpose programming language that is easy to learn and use. It is also very versatile and can be used to automate a wide variety of tasks.
      Python is one of the most in-demand programming languages for automation, and the demand for Python automation skills is expected to continue to grow in the coming years.

    • @nothingburger7
      @nothingburger7 Рік тому

      Thank you so much@@RaghavPal

  • @yo.c.d2014
    @yo.c.d2014 27 днів тому

    well done!!!!!!!!!! ❤ from israel

  • @LongHoàng-m6l
    @LongHoàng-m6l 2 місяці тому

    how to connect database ?

    • @RaghavPal
      @RaghavPal  2 місяці тому

      Long
      Playwright is primarily designed for end-to-end testing and browser automation. It excels at interacting with web pages and simulating user actions. However, it doesn't have built-in capabilities to directly connect to databases.
      The Bridge: Your Server-Side Code
      To work with a database in your Playwright tests, you'll need a bridge between your frontend (the browser controlled by Playwright) and your backend (where your database lives). This bridge is typically your server-side code (e.g., using Node.js, Python, etc.) and a REST API or similar communication mechanism.
      Typical Flow:
      Playwright Action: Your Playwright test performs actions in the browser (e.g., filling out a form, clicking a button)
      API Request: These actions trigger API requests from your frontend to your backend server
      Server-Side Logic: Your server-side code receives these requests, processes them, and interacts with your database (using a database library appropriate for your chosen server-side language and database type)
      API Response: Your server sends a response back to the frontend (your Playwright-controlled browser)
      Playwright Assertions: Your Playwright test then checks the browser's state or the API response to verify that the database interaction produced the expected results.
      Example (Conceptual):
      JavaScript
      // In your Playwright test:
      await page.fill('#username', 'testuser');
      await page.fill('#password', 'testpassword');
      await page.click('#login-button');
      // Your server-side code (example using Node.js and Express):
      app.post('/login', async (req, res) => {
      const { username, password } = req.body;
      // ... database query to check credentials ...
      if (/* credentials are valid */) {
      res.json({ success: true });
      } else {
      res.status(401).json({ error: 'Invalid credentials' });
      }
      });
      // Back in your Playwright test:
      await page.waitForResponse('/login');
      // ... assert that the login was successful ...
      Use code with caution.
      Key Points:
      Separation of Concerns: Keep your Playwright tests focused on browser interactions and your server-side code responsible for database operations.
      API Design: Design a clear and well-structured API to facilitate communication between your frontend and backend.
      Database Library: Choose a suitable database library for your server-side language and database (e.g., mysql, mongoose for MongoDB, etc.).
      Remember, Playwright is a powerful tool for browser automation, but database interactions are typically handled on the server-side
      -

  • @alexanderkomanov4151
    @alexanderkomanov4151 Рік тому

    Thank you very much!!!

  • @AnimalLoverFact
    @AnimalLoverFact Рік тому

    Please improve the sound, sounds is very less coming...

    • @RaghavPal
      @RaghavPal  Рік тому

      ok, will take care from next lecture

  • @RajaVenkateshTheKing
    @RajaVenkateshTheKing 7 місяців тому

    Thank you Raghav!

    • @RaghavPal
      @RaghavPal  7 місяців тому

      Most welcome Raja

  • @baburoyal9894
    @baburoyal9894 Рік тому

    Thanks sir

  • @jojasti
    @jojasti 11 місяців тому

    Please eat before recording a new video. You are muted. We can not hear you on 100% volume

    • @RaghavPal
      @RaghavPal  11 місяців тому

      sorry to know this, I will improve on this