Easiest way | Playwright Page Object Model | Step by Step DEMO

Поделиться
HTML-код
  • Опубликовано: 14 дек 2024

Комментарии • 207

  • @allenstroud4236
    @allenstroud4236 Год назад +4

    You are a great instructor and your presentation is top notch! I'm following along and this is exactly what I've been looking for. Thank you!

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Allen, thanks a lot for the message

  • @Bercilakdehautdesert-yt1gd
    @Bercilakdehautdesert-yt1gd 7 месяцев назад

    One of the best instructional videos I've seen since I started Web dev in 1994. What I found hugely useful was the way you explained how it all wires together, and where there was a problem we got to see the impact, for example the need to use "await" with "async".
    Thank you Raghav. I have just added a Hedgehog Step to my pond, so if the baby hoglets fall in they will be saved, thanks to your kind request to help animals in return for your course :-) Also subscribed of course!

    • @RaghavPal
      @RaghavPal  7 месяцев назад +1

      So happy and humbled to see your message.. thanks for helping the animals

  • @RogerGould-p5k
    @RogerGould-p5k 9 месяцев назад

    This is great, very clear steps on what you are doing. One of the best I have seen. Thanks!

    • @RaghavPal
      @RaghavPal  9 месяцев назад

      Most welcome Roger.. humbled..

  • @SineQuaNon1
    @SineQuaNon1 Год назад

    Many thanks. That was a great video. How simply you taught to create a POM project. I watched many other videos on Playwright POM. This is definitely the best. Meantime, I wouldn't be so rude to teach you anything, but at min 9.30-11.00, to run one single test, I think we can use "npx playwright test tests/demo/login.spec.js --project chromium --headed"

    • @RaghavPal
      @RaghavPal  Год назад +1

      thanks for the information

  • @cnjbravo
    @cnjbravo 7 месяцев назад

    This is just great, I was looking for this since 1 week ago, I have the same login in different test, so if I have to change something then I have to do it in all tests, now using POM I'll only have to maintain one login page. Thanks Raghav.

    • @RaghavPal
      @RaghavPal  7 месяцев назад

      Great to know this Jorge.. keep learning

  • @mzamomahaeng268
    @mzamomahaeng268 Год назад

    Priceless!!!! you just have the skill to impart knowledge perfect!! Keep it up sir

  • @PravinKalubarme
    @PravinKalubarme 6 месяцев назад

    Thank you so much Raghav.
    Very helpful tutorial on playwright.
    Few more video on framework would really helpful.

  • @TheMMakif
    @TheMMakif Год назад

    Thank you for this very useful series. I did learn the basics of playwright and now I can learn deeper aspects of this tool. Very clean and smooth explanations with spot on examples. 👍

    • @RaghavPal
      @RaghavPal  Год назад +1

      You're very welcome Akif

  • @ShyamNithyanandham
    @ShyamNithyanandham Год назад

    Thanks for the informative session Raghav. Your details explanation will surely help the new starts like me. Once again thanks for your effort.

  • @aceage5910
    @aceage5910 Год назад +1

    Hi,
    I was Implementing POM for one of my project following your instructions.
    I made a home.js file in which I have made a class and in that class created container where i get elements needed and function in which I am going to the specific page and clicking a button. and that should navigate to other page.
    In my test.spec.js file I ran that function and after running that function I have written an assertion toHaveURL but it is not getting the new URL.
    It is always recieving old URL but it should get new URL as in the function I have clicked on the button to go to that URL.

    • @RaghavPal
      @RaghavPal  Год назад +2

      Hi,
      There could be a few reasons why the assertion is not receiving the new URL. Here are a few things you can check:
      Wait for Navigation: When you click a button that navigates to another page, there is a delay between the button click and the navigation to the new page. To ensure that the navigation has completed before checking the URL, you can use the await page.waitForNavigation() method.
      Page Loading: Sometimes the page can take some time to load fully, even after the navigation has completed. To ensure that the page has fully loaded before checking the URL, you can use the await page.waitForSelector() method with a selector that is unique to the new page.
      Incorrect URL: Make sure that you are checking the correct URL. It's possible that the URL you expect to see is different from what you are actually seeing. You can check the actual URL by logging it to the console using console.log(page.url).
      Here's an example of how you can modify your test.spec.js file to incorporate these checks:
      describe('Navigation Test', () => {
      it('Should navigate to the correct URL', async () => {
      const home = new Home();
      await home.goToPage();
      // Wait for navigation to complete
      await page.waitForNavigation();
      // Wait for page to load fully
      await page.waitForSelector('unique-selector-on-new-page');
      // Check the actual URL
      console.log(page.url);
      // Assert that the URL is the expected URL
      expect(page.url).toHaveURL('expected-url');
      });
      });
      I hope these suggestions help you resolve the issue and get the expected URL. If you're still having trouble, please provide more information about your implementation and the error message you're receiving.

  • @socialnetworkingtube
    @socialnetworkingtube Год назад +1

    hi thanks for wonderful video. i have one question . i am running headed execution in playwright and want to stop the browser from closing automatically after execution and close it manually instead. pls could you help?
    using javascript

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Sujata
      To stop the browser from closing automatically after execution in Playwright and close it manually instead using JavaScript, you can use the following code:
      ```
      const browser = await playwright.chromium.launch({ headless: false });
      const context = await browser.newContext();
      const page = await context.newPage();
      // Do your stuff here...
      // Stop the browser from closing automatically after execution
      await page.evaluate(() => {
      window.onbeforeunload = null;
      });
      // Close the browser manually using JavaScript
      await page.close();
      await browser.close();
      ```
      This code will first create a new Chromium browser in headless mode. Then, it will create a new context and page. You can do your stuff here, such as visiting a web page or interacting with an application.
      To stop the browser from closing automatically after execution, the code will set the `window.onbeforeunload` event handler to `null`. This event handler is called when the user is about to navigate away from the page. By setting it to `null`, the browser will not close automatically when the user navigates away from the page.
      Finally, the code will close the browser manually using JavaScript. This will ensure that the browser does not close automatically after execution.
      I hope this helps

    • @socialnetworkingtube
      @socialnetworkingtube Год назад

      thank you so much @@RaghavPal 🙏

  • @hilalbulut3379
    @hilalbulut3379 Год назад

    an incredibly good tutorial - thank you so much for the great videos, Raghav 👏👏👏👏👏👏👏

  • @Ezhilthendral
    @Ezhilthendral Год назад

    Thank you very much Ragav!. Very clear and easy to understand! Great job!.

  • @JoolieEm
    @JoolieEm Год назад

    Fantastic job! I finished the whole training, thank you so much for your work! 🙏

    • @RaghavPal
      @RaghavPal  Год назад

      You're so welcome Justyna

  • @KasuriThiyumini
    @KasuriThiyumini Год назад

    You have been an incredible mentor and role model for me, and I am so thankful for your guidance. I would appreciate your guidance on how to handle pop-up alerts for entering a login and password. Thanks a lot.

    • @RaghavPal
      @RaghavPal  Год назад

      You are so welcome Kasuri
      To handle pop-up alerts for entering a login and password in Playwright, you can use the following steps:
      1. Listen for the `dialog` event.
      2. Get the text of the dialog.
      3. If the text of the dialog is a login prompt, enter the username and password.
      4. Click the OK button.
      Here is an example of how to handle pop-up alerts for entering a login and password in Playwright:
      ```
      import { test, expect } from '@playwright/test';
      test('Handle pop-up alerts for entering a login and password', async ({ page }) => {
      // Listen for the `dialog` event.
      await page.on('dialog', async dialog => {
      // Get the text of the dialog.
      const text = dialog.message();
      // If the text of the dialog is a login prompt, enter the username and password.
      if (text.includes('Login')) {
      await dialog.accept('username', 'password');
      } else {
      // Dismiss the dialog.
      await dialog.dismiss();
      }
      });
      // Navigate to a page that opens a pop-up alert for entering a login and password.
      await page.goto('example.com/login');
      });
      ```
      You can also use a third-party library to handle pop-up alerts for entering a login and password. For example, the `Playwright Extras` library includes a `LoginDialog` class that can help you handle login dialogs.
      I hope this helps

    • @KasuriThiyumini
      @KasuriThiyumini Год назад

      Many Thanks Again. It is working now. 🙏🙏🙏@@RaghavPal

  • @peterinvestor
    @peterinvestor 6 месяцев назад

    Whats the reason/purpose of having pages folder outside tests? Who not to create subfolder in tests and keep POM files there?

    • @RaghavPal
      @RaghavPal  6 месяцев назад

      Peter
      The main reason for having a separate "pages" folder outside of the "tests" folder in the Page Object Model (POM) structure is to separate the concerns of test scripts and page objects. This separation helps to keep the codebase organized, maintainable, and scalable. Here are some reasons why it's beneficial to keep the "pages" folder outside of the "tests" folder:
      1. Separation of Concerns: By keeping page objects separate from test scripts, you can clearly distinguish between the two responsibilities. Page objects represent the web pages or components being tested, while test scripts focus on the specific test scenarios and interactions with those page objects.
      2. Reusability: Placing page objects in a separate folder allows for better code reuse. Page objects can be shared across multiple test scripts without duplicating code. This promotes consistency and reduces maintenance efforts.
      3. Scalability: As the number of test scripts and page objects grows, having a separate "pages" folder helps maintain a clear structure. It is easier to locate and manage page objects when they are organized separately from the test scripts.
      4. Testing Independence: Separating page objects from test scripts ensures that changes made to the page structure or elements do not directly impact the test scripts. This makes it easier to update page objects independently without affecting the test logic.
      5. Code Modularity: Placing page objects in a separate folder promotes code modularity and encapsulation. Page objects can be designed to represent the web elements, actions, and verifications specific to a single page or component, making the code more modular and reusable.
      While it is technically possible to create subfolders within the "tests" folder to organize page objects, keeping them separate in a dedicated "pages" folder follows best practices in Test Automation and enhances the readability, maintainability, and scalability of your test suite.
      --

  • @elysium306
    @elysium306 Год назад

    Thank you for making this wonderful video series!!

    • @RaghavPal
      @RaghavPal  Год назад

      Glad you enjoy it Elysium

  • @nicholasamodu6676
    @nicholasamodu6676 9 месяцев назад

    i appreciate your teaching sir.

    • @RaghavPal
      @RaghavPal  9 месяцев назад

      Glad to hear that Nicholas

  • @nicholasamodu6676
    @nicholasamodu6676 9 месяцев назад

    sir pls my report is not showing the dropdown like yours. the last page object model

    • @RaghavPal
      @RaghavPal  9 месяцев назад

      Nicholas
      it may be due to different version of Playwright.. can check documentation

  • @suhasch12
    @suhasch12 Год назад

    To find locator it's giving option of "Get by Role" and Get by Lable", could you please elaborate on this one and a quick video on this will also be helpful on what to use, Thank you

    • @RaghavPal
      @RaghavPal  Год назад +1

      In Playwright, the options "Get by Role" and "Get by Label" are two different locator strategies that you can use to locate elements on a web page. Here's a brief explanation of each strategy:
      1. Get by Role:
      - This strategy allows you to locate elements based on their role or purpose in the web page's user interface.
      - It is useful when you want to interact with elements based on their functionality or expected behavior.
      - For example, you can locate a button with the role of "button" or a checkbox with the role of "checkbox" using this strategy.
      2. Get by Label:
      - This strategy allows you to locate elements based on their associated label or text.
      - It is useful when elements are labeled with descriptive text, such as form fields with corresponding labels.
      - For example, you can locate an input field with the label "Email" or a button with the label "Submit" using this strategy.
      Choosing the appropriate locator strategy depends on the structure and attributes of the web page you are testing. It's recommended to use a strategy that provides a stable and unique way to locate the desired elements.
      Regarding a quick video demonstration, as a text-based AI model, I'm unable to provide videos. However, you can search for Playwright tutorials or demonstrations on popular platforms like RUclips, where you may find helpful videos explaining how to use different locator strategies in Playwright and showcasing practical examples.
      Additionally, you can refer to the official Playwright documentation, which provides detailed information and examples on various locator strategies supported by Playwright.
      Remember that the availability and effectiveness of different locator strategies may vary depending on the specific web page you are testing, so it's important to experiment and choose the strategy that works best for your particular scenario.

    • @suhasch12
      @suhasch12 Год назад

      @@RaghavPal Thank you very much for sharing the additional details, if makes life easier to use these for locator strategy as most of the elements will have either of these 2 locators and its easy to find them on DOM

  • @Lisa-nb8hw
    @Lisa-nb8hw Год назад +1

    Great videos! It was so helpful.
    Q: Can I automate to email the playwright test results ?

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Lisa
      Yes, you can automate the process of emailing the Playwright test results using a package like nodemailer in Node.js.
      Here are the basic steps to achieve this:
      Install the nodemailer package by running npm install nodemailer in your project directory.
      Create a function that will send the email using nodemailer. This function should take in the test results as a parameter, and should contain the details of the email, such as the recipient email address, subject line, and body.
      Here is an example code snippet:
      const nodemailer = require('nodemailer');
      async function sendResultsEmail(testResults) {
      let transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
      user: 'your_email@gmail.com',
      pass: 'your_email_password'
      }
      });
      let mailOptions = {
      from: 'your_email@gmail.com',
      to: 'recipient_email@example.com',
      subject: 'Playwright Test Results',
      text: testResults
      };
      let info = await transporter.sendMail(mailOptions);
      console.log(`Email sent: ${info.messageId}`);
      }
      In the above code, replace the your_email@gmail.com and your_email_password with your own Gmail account credentials. Also, replace recipient_email@example.com with the email address of the recipient of the email.
      Call the sendResultsEmail() function after running the Playwright tests, and pass in the test results as a parameter. You can get the test results by storing them in a variable or by reading them from a file.
      Here is an example code snippet:
      const { chromium } = require('playwright');
      const fs = require('fs');
      (async () => {
      const browser = await chromium.launch();
      const page = await browser.newPage();
      await page.goto('example.com');
      // run Playwright tests here
      const testResults = await page.evaluate(() => {
      // get test results here
      });
      await browser.close();
      // write test results to a file
      fs.writeFileSync('test-results.txt', testResults);
      // send email with test results
      await sendResultsEmail(testResults);
      })();
      In the above code, replace the example.com with the URL of the website you want to test. Also, replace the // get test results here with the code to retrieve the Playwright test results. Finally, replace the 'test-results.txt' with the file path where you want to store the test results.

    • @Lisa-nb8hw
      @Lisa-nb8hw Год назад

      ​ @Automation Step by Step thank you so much for the information, I might used this to my current tests. But I hope I could get a video demo from you with regards to this :D

  • @lailabernardon443
    @lailabernardon443 3 месяца назад

    Hello, thanks by share! One question, is about around the 11:35 minutes that you said about run the tests 3 times because of each browser, how it is set to specify the browsers that I want to test?

    • @RaghavPal
      @RaghavPal  3 месяца назад

      Laila
      you can use this command:
      npx playwright test --browser=chromium,firefox,webkit --repeat=3
      This command will run the test 3 times, once on each browser
      npx playwright test --browser=chromium,firefox,webkit --repeat=3 -- shard=3
      This will run the test 9 times in total: 3 times on each of the 3 browsers.
      You can also specify the browsers and repetitions in your playwright.config.js file:
      module.exports = {
      // ...
      browsers: ['chromium', 'firefox', 'webkit'],
      repeat: 3,
      shard: 3,
      // ...
      }
      Then, you can run the test using the following command:
      npx playwright test
      -

    • @lailabernardon443
      @lailabernardon443 3 месяца назад

      @@RaghavPal thanks 🙌🏻 I will try in python

  • @sarayum7934
    @sarayum7934 11 месяцев назад

    hi Raghav, I get the error Can't push refs to remote try running pull first to integrate your changes while publishing the code. Please help

    • @RaghavPal
      @RaghavPal  11 месяцев назад

      Sarayu
      For the "Can't push refs to remote" error, can try this:
      1. Fetch and Integrate Remote Changes:
      - Run `git pull`: This fetches any new commits from the remote repository and attempts to merge them with your local branch.
      - Resolve conflicts: If conflicts arise, manually address them in your code editor and stage the resolved files using `git add`.
      - Commit the merged changes: Use `git commit` to create a new commit with the merged changes.
      2. Rebase for Cleaner History (Optional):
      - Prefer a linear history: If you want a cleaner commit history without merge commits, use `git pull --rebase` instead of `git pull`. This replays your local commits on top of the updated remote branch.
      3. Push Your Changes:
      - Attempt `git push` again: Once conflicts are resolved and changes are committed, retry pushing your code to the remote repository using `git push origin `.
      Additional Considerations:
      - Force push with caution: If you're certain there won't be conflicts, use `git push -f` to overwrite the remote branch, but use it sparingly as it can lead to data loss.
      - Check permissions: Ensure you have sufficient permissions to push to the remote branch. If not, coordinate with repository maintainers.
      - Verify branch names: Double-check that you're pushing to the correct branch.
      - Update remote references: In rare cases, you might need to update remote references manually using `git fetch --prune`.

  • @sowjireddy8767
    @sowjireddy8767 Год назад

    great content..👍
    Very useul & lot of knowledge

  • @MamzP_007
    @MamzP_007 6 месяцев назад

    Hi ​ @RaghavPal
    I have a question that might be a little different. I'm interested in extracting text from a website. Specifically, I want to grab all the text that appears after a certain word.
    For example, let's say a website has various sections where the word "play" is used, followed by different descriptions. I'd like to find a way to automatically collect all the text that comes after "play" on that page.
    Is there a method to achieve this?

    • @RaghavPal
      @RaghavPal  6 месяцев назад +1

      To extract text after a specific word on a webpage, you can use different approaches depending on the context and the tools you have available. Here are some methods you can consider:
      1. Using Playwright (Python/JavaScript):
      - If you're using Playwright, you can automate web interactions and extract text from specific elements on a webpage. You'll need to locate the relevant section containing the word "play" and then retrieve the text following it.
      - For example, in Python, you can use Playwright to find the element containing the word "play" and then extract the text after it.
      2. Using Regular Expressions (Python/JavaScript):
      - Regular expressions (regex) are powerful for pattern matching. You can search for occurrences of the word "play" and capture the text that follows it.
      - In Python, you can use the `re` module to achieve this. For example:
      ```python
      import re
      # Assuming 'html_content' contains the webpage content
      matches = re.findall(r'play\s*(.*?)\s*', html_content, flags=re.IGNORECASE)
      # 'matches' will contain all text following the word "play"
      ```
      3. Using Excel (TEXTAFTER function):
      - If you want to extract text from a specific section of a webpage and analyze it later, you can copy the relevant content into an Excel sheet.
      - In Excel, you can use the `TEXTAFTER` function to extract text after a specific word. For instance, if the word is "play," you can use:
      ```
      =TEXTAFTER(A1, "play")
      ```
      where `A1` contains the relevant section of text.
      4. Using JavaScript (Browser Console):
      - If you're inspecting a webpage in a browser, you can open the browser console and run JavaScript code to extract text.
      - For example, in the browser console, you can use:
      ```javascript
      const word = 'play';
      const elements = document.querySelectorAll('*:contains("' + word + '")');
      const extractedText = Array.from(elements).map(el => el.textContent);
      console.log(extractedText);
      ```
      Remember that the specific implementation will depend on the tools and context you're working with. Choose the method that best suits your requirements and programming environment
      --

  • @michaeledmondson-f7q
    @michaeledmondson-f7q Год назад

    Hey im getting this error 'cannot read properties of undefined (reading 'locator') playwright"

    • @RaghavPal
      @RaghavPal  Год назад

      Michael
      The error message `cannot read properties of undefined (reading 'locator') playwright` means that Playwright is trying to access a property on an undefined object. This can happen for a few reasons:
      * You are trying to access a locator before it has been initialized.
      * You are trying to access a locator that has been destroyed.
      * You are trying to access a locator that does not exist.
      To fix this error, you need to make sure that the locator is initialized and that it exists before you try to access it.
      Here are some things you can try:
      * Check that you are calling the `locator.waitFor()` method before you try to access the locator.
      * Check that you are not using the locator after it has been destroyed.
      * Check that the locator is valid. You can do this by using the `locator.isPresent()` method.
      If you are still having trouble fixing this error, please provide more information about your code, such as the code that is throwing the error and the code that you are using to initialize and access the locator.
      Here are some additional tips for avoiding this error:
      * Use the `locator.waitFor()` method to make sure that the locator is initialized before you try to access it.
      * Use the `locator.isPresent()` method to check that the locator exists before you try to access it.
      * Avoid using locators after they have been destroyed.
      * Use descriptive names for your locators. This will make it easier to debug your code if you encounter this error.
      I hope this helps

  • @sonicc.s7033
    @sonicc.s7033 Год назад

    Sir what is the code to swithch from one window to another in playwright like we have driver.SwtichtoWindow() in selenium

    • @RaghavPal
      @RaghavPal  Год назад

      To switch from one window to another in Playwright, you can use the `switchTo()` method. The `switchTo()` method takes a window handle as its argument. The window handle is a unique identifier for a window. You can get the window handle by using the `windowHandle()` method.
      The following code shows how to switch from one window to another in Playwright:
      // Get the current window handle.
      const currentWindowHandle = await page.handle();
      // Get the window handle of the window you want to switch to.
      const targetWindowHandle = await page.windowHandles().find(handle => handle !== currentWindowHandle);
      // Switch to the target window.
      await page.switchTo(targetWindowHandle);
      The `switchTo()` method will throw an error if the window handle is invalid.
      Here is an example of how to use the `switchTo()` method to switch from the main window to a new window that was opened by a link:
      ```
      // Click on the link to open a new window.
      await page.click("link");
      // Get the window handle of the new window.
      const newWindowHandle = await page.windowHandles().find(handle => handle !== currentWindowHandle);
      // Switch to the new window.
      await page.switchTo(newWindowHandle);
      ```
      I hope this helps

  • @serdarfesli2433
    @serdarfesli2433 Год назад

    thanks a lot raghav. what should I do if I want to use action methods like click in my test. I don't want to include this in POM file

    • @RaghavPal
      @RaghavPal  Год назад +1

      Serdar
      You can do that instead of calling function from the page class, you can directly add the script for action in test class, although that will not be according to POM modal

    • @serdarfesli2433
      @serdarfesli2433 Год назад

      @@RaghavPal thanks a lot Raghav. appreciate your time and effort.

  • @himats7195
    @himats7195 9 месяцев назад

    Hello Raghav, need your advise and help. How do we use Maps in Playwright. Need to validate the keys and their values. Please guide. TIA.

    • @RaghavPal
      @RaghavPal  9 месяцев назад

      Hima
      Can try these steps:
      1. Interacting with Maps:
      To interact with a map component (like Google Maps or OpenStreetMaps) using Playwright, you can simulate mouse movements to drag the map around. Here's an example using Playwright to move the map:
      ```javascript
      const { chromium } = require("playwright");
      (async () => {
      const browser = await chromium.launch({ headless: false });
      const page = await browser.newPage();
      await page.goto("www.openstreetmap.org/"); // Replace with your map URL
      await page.mouse.move(600, 300); // Move to a specific position
      await page.mouse.down(); // Press the mouse button
      await page.mouse.move(1200, 450); // Move to another position
      await page.mouse.up(); // Release the mouse button
      await browser.close();
      })();
      ```
      Adjust the coordinates and map URL according to your use case. Note that you might need to ensure your viewport size is large enough for the map movement¹.
      2. Validating Keys and Values:
      To validate keys and values on a map, you can use Playwright's assertions. For example, if you want to verify the text of an element with a specific test ID, you can use `toHaveText`:
      ```javascript
      await expect(page.getByTestId('status')).toHaveText('Submitted');
      ```
      This assertion will retry until the fetched element has the expected text (in this case, "Submitted"). You can adjust the timeout or configure it globally via `testConfig.expect`⁹.
      Remember to replace the map URL and adapt the code to your specific scenario.
      ..

    • @himats7195
      @himats7195 9 месяцев назад

      @@RaghavPal thank you v much

  • @maddulasaikrishna7586
    @maddulasaikrishna7586 Год назад

    How can I use javascript library such as moment.js in Playwright for typing date & time automatically in date & time field

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Maddula
      To use a JavaScript library like moment.js in Playwright to automatically type date and time in a field, you can follow these steps:
      1. Install moment.js: Use npm or yarn to install moment.js as a dependency in your project. Open a terminal in your project directory and run the following command:
      ```
      npm install moment
      ```
      2. Import moment.js: In your Playwright test script, import the moment.js library using the `require` or `import` statement. For example:
      ```javascript
      // Using require
      const moment = require('moment');
      // Using import
      import moment from 'moment';
      ```
      3. Use moment.js to generate the desired date and time values: Utilize moment.js functions to generate the desired date and time values based on your requirements. For example:
      ```javascript
      // Get current date and time
      const currentDateTime = moment().format('YYYY-MM-DD HH:mm:ss');
      // Get a future date and time
      const futureDateTime = moment().add(1, 'days').format('YYYY-MM-DD HH:mm:ss');
      ```
      4. Use Playwright to interact with the date and time field: Use Playwright's APIs to locate the date and time field on the web page and enter the generated date and time values. For example:
      ```javascript
      // Locate the date and time field
      const dateTimeField = await page.$('#datetime-input');
      // Clear the field and type the current date and time
      await dateTimeField.clear();
      await dateTimeField.type(currentDateTime);
      // Clear the field and type a future date and time
      await dateTimeField.clear();
      await dateTimeField.type(futureDateTime);
      ```
      By combining moment.js with Playwright, you can generate dynamic date and time values and easily enter them into date and time fields during your automated tests.

  • @pradipvaghela3179
    @pradipvaghela3179 Год назад

    when i use same code using type script it gives me the error in constructor(page). an erorr is "Parameter 'page' implicitly has an 'any' type, but a better type may be inferred from usage" and second is that, while using "this. page=page " it giving me error "Property 'page' does not exist on type 'LoginPage'.ts" for typescript. please give me the solution of this. thanks

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Pradip
      The errors you are getting are due to the fact that TypeScript is a strongly typed language, and it requires that all variables and parameters have a specific type.
      The error "Parameter 'page' implicitly has an 'any' type, but a better type may be inferred from usage" means that TypeScript cannot infer the type of the `page` parameter from the way it is used in the constructor. This is because the `page` parameter is of type `any`, which means that it can be of any type.
      The error "Property 'page' does not exist on type 'LoginPage'.ts" means that the `page` property does not exist on the `LoginPage` type. This is because the `page` property is not defined in the `LoginPage` class.
      To fix these errors, you need to specify the type of the `page` parameter in the constructor. You can do this by using the `type` keyword. For example, you could change the constructor to the following:
      ```
      constructor(public page: Page) {}
      ```
      This will tell TypeScript that the `page` parameter is of type `Page`, which is a type that is defined by Playwright.
      You also need to define the `page` property in the `LoginPage` class. You can do this by adding the following line to the class definition:
      ```
      public page: Page;
      ```
      This will tell TypeScript that the `page` property is of type `Page`.
      Once you have made these changes, the errors should go away.
      I hope this helps

  • @shelly1067
    @shelly1067 Год назад

    Thank you for the video, I am not able to access method selectOption for selecting any option from drop down in page files where css and path are defined. This method is accessible only in spec file, then how to frame Pom with drop down selection.

    • @RaghavPal
      @RaghavPal  Год назад

      Shelly
      To access the `selectOption()` method for selecting an option from a dropdown in page files where CSS and path are defined, you can use the following steps:
      1. In your page file, create a variable to store the element locator of the dropdown.
      2. Use the `waitForSelector()` method to wait for the dropdown to be present and visible.
      3. Use the `selectOption()` method to select the desired option from the dropdown.
      Here is an example:
      ```javascript
      // Define the element locator for the dropdown.
      const dropdownLocator = '.select-dropdown';
      // Wait for the dropdown to be present and visible.
      await page.waitForSelector(dropdownLocator);
      // Select the desired option from the dropdown.
      await page.selectOption(dropdownLocator, 'my-option');
      ```
      You can also use the `POM` pattern to encapsulate the logic for selecting an option from a dropdown in a separate file. This will make your code more reusable and maintainable.
      Here is an example of a `POM` class for selecting an option from a dropdown:
      ```javascript
      class DropdownSelector {
      constructor(page, locator) {
      this.page = page;
      this.locator = locator;
      }
      async selectOption(optionValue) {
      await this.page.waitForSelector(this.locator);
      await this.page.selectOption(this.locator, optionValue);
      }
      }
      ```
      To use this `POM` class, you can do the following:
      ```javascript
      // Create a new instance of the DropdownSelector class.
      const dropdownSelector = new DropdownSelector(page, '.select-dropdown');
      // Select the desired option from the dropdown.
      await dropdownSelector.selectOption('my-option');
      ```
      By using the `POM` pattern, you can easily select an option from a dropdown in your Playwright tests, regardless of where the CSS and path for the dropdown are defined.

    • @shelly1067
      @shelly1067 Год назад

      @@RaghavPal thank you for the explanation, you always explain everything with such clarity and depth.

  • @sirishapochiraju3551
    @sirishapochiraju3551 Год назад

    Hi Raghav, I am getting pages not defined reference error at ..\pages\login.js:15 not sure how to resolve this

    • @RaghavPal
      @RaghavPal  Год назад +2

      Hi Sirisha
      The error message "pages not defined reference error" means that the `pages` variable is not defined in the file `login.js`. This can happen for a few reasons, including:
      * The file `login.js` is not importing the `pages` module.
      * The `pages` module is not installed.
      * The `pages` module is not defined in the global scope.
      To resolve this error, you need to make sure that the file `login.js` is importing the `pages` module. You can do this by adding the following line to the top of the file:
      ```
      import * as pages from './pages';
      ```
      You also need to make sure that the `pages` module is installed. You can do this by running the following command in your terminal:
      ```
      npm install pages
      ```
      Finally, you need to make sure that the `pages` module is defined in the global scope. You can do this by adding the following line to the top of your `package.json` file:
      ```
      "dependencies": {
      "pages": "^1.0.0"
      }
      ```
      Once you have made these changes, the error should be resolved.
      Here are some additional things to keep in mind:
      * The `pages` module is a collection of pages that can be used for testing.
      * The `pages` module is typically installed as a dependency of your test framework.
      * The `pages` module is typically defined in the global scope so that it can be accessed from any file in your project.
      I hope this helps! Let me know if you have any other questions.

    • @sirishapochiraju3551
      @sirishapochiraju3551 Год назад

      @@RaghavPal Thanks raghav it worked !

  • @waseemakram9082
    @waseemakram9082 Год назад

    thanks for course. i am stuck in implementing POM. I want to login then navigate to admin url and then perform crud operations. i am stuck can you please provide solution how can i achieve this?
    1. I need to login - Done
    2. navigage to admin url - not done
    3. Add user - not done
    4. update user - not done
    5. delete user - not done

    • @RaghavPal
      @RaghavPal  Год назад

      Waseem
      Here's a step-by-step approach to implement POM (Page Object Model) in Playwright to perform login, navigate to admin URL, and perform CRUD operations on users.
      **1. Create Page Objects for Login and Admin Pages**
      Create separate page objects for the login page and the admin page. Each page object should encapsulate the interactions specific to that page, such as entering login credentials, clicking login buttons, or navigating to admin URL.
      **2. Implement Login Page Object**
      In the login page object, define methods for entering login credentials and submitting the login form. For example:
      ```javascript
      class LoginPage {
      constructor(page) {
      this.page = page;
      }
      async enterUsername(username) {
      await this.page.locator('input[name="username"]').fill(username);
      }
      async enterPassword(password) {
      await this.page.locator('input[name="password"]').fill(password);
      }
      async clickLoginButton() {
      await this.page.locator('button[type="submit"]').click();
      }
      }
      ```
      **3. Implement Admin Page Object**
      In the admin page object, define methods for navigating to the admin URL and performing CRUD operations on users. For example:
      ```javascript
      class AdminPage {
      constructor(page) {
      this.page = page;
      }
      async navigateToAdminURL() {
      await this.page.goto('/admin');
      }
      async addUser(user) {
      // Implement logic to add a new user
      }
      async updateUser(user) {
      // Implement logic to update an existing user
      }
      async deleteUser(userId) {
      // Implement logic to delete a user by ID
      }
      }
      ```
      **4. Create Test Script**
      Create a test script that orchestrates the login, navigation to admin URL, and CRUD operations. For example:
      ```javascript
      const playwright = require('playwright');
      (async () => {
      const browser = await playwright.chromium.launch({ headless: false });
      const page = await browser.newPage();
      // Create login page object
      const loginPage = new LoginPage(page);
      // Perform login
      await loginPage.enterUsername('username');
      await loginPage.enterPassword('password');
      await loginPage.clickLoginButton();
      // Create admin page object
      const adminPage = new AdminPage(page);
      // Navigate to admin URL
      await adminPage.navigateToAdminURL();
      // Perform CRUD operations
      // ...
      await adminPage.addUser({ name: 'John Doe', email: 'johndoe@example.com' });
      await adminPage.updateUser({ id: 1, name: 'Jane Doe' });
      await adminPage.deleteUser(2);
      await browser.close();
      })();
      ```
      This example demonstrates the basic structure of implementing POM using Playwright. You'll need to adapt the specific implementation details to your application's login, admin page, and user management functionalities.

  • @maddulasaikrishna7586
    @maddulasaikrishna7586 Год назад

    Hello ,
    i want to create Generic Functions For click & type in textbox in separate file , in that which libraries i need to call. can you give example for click operation.
    i have tried like this ,but when i hover mouse on page it is showing any.
    import { page, test, expect} from '@playwright/test';
    class Input_Utility{
    async ElementClick_Utility(Element,ElementDesc){
    await page.click(Element);
    console.log(ElementDesc.green+" is Clicked")
    //Logged comment to be added
    }export default Input_Utility;
    can you hlep .

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Maddula
      To create generic functions for click and type operations in Playwright, you need to import the necessary libraries:
      import { Page } from '@playwright/test';
      In your example, you are missing the Page library. You also need to pass the page object as a parameter to the function. Here is an updated example for the click operation:
      import { Page } from '@playwright/test';
      export async function clickElement(page: Page, elementSelector: string, elementDesc: string) {
      await page.click(elementSelector);
      console.log(`${elementDesc} is clicked.`);
      }
      In the above code, we have created a function named clickElement that takes page, elementSelector, and elementDesc as parameters. page is the page object that we need to pass to the function when we call it. elementSelector is a string that represents the selector of the element we want to click. elementDesc is a string that represents the description of the element.
      You can call the clickElement function in your test like this:
      import { test, expect } from '@playwright/test';
      import { clickElement } from './input-utility';
      test('Click button', async ({ page }) => {
      await page.goto('example.com');
      await clickElement(page, 'button#submit', 'Submit button');
      // assert something
      });
      In the above code, we have imported the clickElement function from the input-utility file and called it in our test. We have passed the page object, button#submit as the elementSelector, and 'Submit button' as the elementDesc to the function. The function will click the button and log a message to the console.

    • @Snehaandsahasra
      @Snehaandsahasra 8 месяцев назад

      @@RaghavPal await clickElement(page, 'button#submit', 'Submit button'); . Here in place of 'button#submit' ,can we write "pageobject.element" . I tried using this way , but it says "expected string but received object" . .Can we only use selector directly in test class instead of using pageobject.element?

  • @sanjeev8720
    @sanjeev8720 Год назад

    Hello sir can you please suggest how to handle below scenario..
    Entering mainurl ..and this url is navigating to different url to enter credentials after entering credentials it is navigating to mainurl only..
    This scenario is working is VS code with playwright javascript but same is not working in concourse server..can you please explain this sir

    • @RaghavPal
      @RaghavPal  Год назад

      Sanjeev
      To handle the scenario where you enter a mainurl that navigates to a different url to enter credentials and then navigates back to the mainurl, you can use the following steps:
      1. Use the `goto` method to navigate to the mainurl.
      2. Use the `waitForNavigation` method to wait until the browser has navigated to the new url.
      3. Use the `fill` method to enter the credentials into the form.
      4. Use the `click` method to click on the submit button.
      5. Use the `waitForNavigation` method to wait until the browser has navigated back to the mainurl.
      Here is an example of how to do this in Playwright JavaScript:
      ```
      const browser = await playwright.chromium.launch();
      const page = await browser.newPage();
      await page.goto('example.com');
      await page.waitForNavigation();
      await page.fill('input[name="username"]', 'username');
      await page.fill('input[name="password"]', 'password');
      await page.click('button[type="submit"]');
      await page.waitForNavigation();
      console.log('Navigated back to mainurl');
      await browser.close();
      ```
      If this scenario is working in VS Code with Playwright JavaScript but not working in Concourse Server, it is likely that there is a problem with the Concourse Server configuration. You can try the following:
      * Make sure that the Concourse Server is running the latest version of Playwright.
      * Make sure that the Concourse Server has access to the necessary native libraries for Playwright.
      * Check the Concourse Server logs for any errors.
      * Contact the Concourse Server support team for help.
      I hope this helps

  • @mustafaezzi2871
    @mustafaezzi2871 Год назад

    Hi Raghav. Does the series end here or there are more videos on playwright coming along ? I would appreciate if more topics are discussed in this series

    • @RaghavPal
      @RaghavPal  Год назад

      Mustafa
      can check all playlists here - automationstepbystep.com/

  • @Mr47CRO
    @Mr47CRO 9 месяцев назад

    Great videos but on this I have a question.
    When I try to run npm init -y on terminal in VS code, I get an basically empty json.package file with an empty description object. Why is that?

    • @RaghavPal
      @RaghavPal  9 месяцев назад +1

      James
      When you run the `npm init -y` command, it initializes a new Node.js project and creates a `package.json` file with default values for the project configuration. The `-y` flag tells npm to skip the questionnaire and generate the file with these defaults. This is why you're seeing a package.json file with minimal information and an empty description object..
      The `package.json` file created by `npm init -y` will typically include the following fields with default or empty values:
      ```json
      {
      "name": "name-of-the-directory",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
      }
      ```
      The `description` field is empty because it's a placeholder for you to provide a description of your project. You can manually edit the `package.json` file to add a description and any other details you want to include about your project..
      If you want to provide specific details during the initialization process, you can run `npm init` without the `-y` flag and answer the prompts to customize your `package.json` file. Alternatively, you can create a `.npm-init.js` file in your home directory to customize the default values used by `npm init -y`

    • @Mr47CRO
      @Mr47CRO 9 месяцев назад +1

      @@RaghavPal Raghav thank you! You are an amazing and extremely knowledgeable man. I wish you all the best and if there were more people like you in this world it would be a better place!

  • @akansha8903
    @akansha8903 Год назад

    Thanks for the Tutorial Raghav🫶🏼
    But I have a doubt suppose a website has a video and I want to run playwright end to end test with id in typescript..how should I do it?

    • @RaghavPal
      @RaghavPal  Год назад

      Akansha
      Sure, here is how you can run a Playwright end-to-end test with an ID in TypeScript:
      ```typescript
      import { test, expect } from '@playwright/test';
      test('should play video in ', async ({ page }) => {
      await page.goto('example.com/video-page');
      const = page.frameLocator('#video-');
      const playButton = .locator('button[aria-label="Play"]');
      await playButton.click();
      await expect().toHaveClass('playing');
      });
      ```
      In this example, the `page.frameLocator()` method is used to locate the with the ID `video-`. The `.locator()` method is then used to locate the play button within the . The `playButton.click()` method is used to click the play button, and the `expect().toHaveClass('playing')` assertion is used to verify that the has the `playing` class.
      This will ensure that the video is playing within the .
      You can use this same approach to interact with any element within an . For example, you could use the `.locator()` method to locate a specific input field within the , and then use the `.locator().fill()` method to enter text into the input field.

  • @sd-kc9qy
    @sd-kc9qy Год назад

    GM Raghav, I enjoy your training video. I am asking in this group about Playwright. I know we can use Playwright for a Web and emulator browser test.
    1) I would like to know if is there any way we can use Playwright and other APIs or other integration to connect the real devices through the ADB command.
    2) If I have an import and export functionality in our browser and wanted to import the file and cross-check a few fields it is correctly imported or not. Do you have video to use import and export functionality using playwright?
    I tried using different playwright option but it was not working.

    • @RaghavPal
      @RaghavPal  Год назад

      Hi SD
      Yes, it is possible to use Playwright and other APIs or integration to connect the real devices through the ADB command. Playwright provides the connectOverAdb method to connect to a device over ADB. You can use this method to create a Browser instance and interact with the device. Here's an example:
      const pw = require('playwright');
      const { devices } = pw;
      (async () => {
      const browser = await pw.connectOverAdb({
      device: 'YOUR_DEVICE_SERIAL_NUMBER',
      browserApp: 'com.android.chrome'
      });
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.goto('www.example.com');
      await page.screenshot({ path: 'example.png' });
      await browser.close();
      })();
      Here's an example of how you can use Playwright to test import and export functionality in a browser:
      const pw = require('playwright');
      (async () => {
      const browser = await pw.chromium.launch({ headless: false });
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.goto('www.example.com');
      // Assume the import button has a CSS selector of "#import-btn"
      await page.click('#import-btn');
      // Assume the file input field has a CSS selector of "#file-input"
      const inputFile = await page.$('#file-input');
      await inputFile.setInputFiles('/path/to/your/file');
      // Wait for the file to be imported and check if the desired fields have been updated
      await page.waitForSelector('#field-to-check');
      const fieldText = await page.$eval('#field-to-check', el => el.textContent);
      console.log(fieldText);
      // Assume the export button has a CSS selector of "#export-btn"
      await page.click('#export-btn');
      // Wait for the file to be downloaded and check if it exists on disk
      await page.waitForEvent('download');
      const downloadsPath = await pw.chromium.downloadsPath();
      const filePath = path.join(downloadsPath, 'exported-file.csv');
      const fileExists = fs.existsSync(filePath);
      console.log(`File downloaded: ${fileExists}`);
      await browser.close();
      })();
      This example assumes that the import and export buttons have specific CSS selectors and that the downloaded file has a specific name and format. You will need to modify it to fit your specific use case.

  • @PurnimaMadhubhashi
    @PurnimaMadhubhashi Год назад +1

    Hi Raghav, Can you please share if you have a tutorial to follow gitlab integration with playwrights? Say if you want to use it in a CI/CD pipleline to run after you created a Merge request

    • @RaghavPal
      @RaghavPal  Год назад +1

      Hi Purnima
      I do not have specific tutorial on GitLab with Playwright, however you can check GitLab playlist and use it with Playwright - automationstepbystep.com/

    • @PurnimaMadhubhashi
      @PurnimaMadhubhashi Год назад

      @@RaghavPal Thanks I will take a look

  • @anandmohandas8307
    @anandmohandas8307 Год назад +1

    Hi Raghav, thanks a lot for your videos, 3 queries
    1)how can we get auto suggestions for the playwright functions inside the POM(Pages class)
    2) Can you show how can we use import statements inside POM, the code is only working if I use require not import
    3) lf i use expect inside the pom i am getting error as below, the browser is closed immediatley its not waiting 30 seconds
    locator.fill: Target closed
    =========================== logs ===========================
    waiting for locator('xpath=//*[@name=\'q\']')
    locator resolved to
    ============================================================
    at ../pages/LoginPage.js:18
    16 | // await this.loginBtn.click()
    17 | await expect(this.search).toBeEnabled()
    > 18 | await this.search.fill('test')
    | ^
    19 | }
    20 | }
    at LoginPage.login (/Users/amohand/Documents/POC/Playwright/pages/LoginPage.js:18:27)

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Anand,
      1)how can we get auto suggestions for the playwright functions inside the POM(Pages class)
      Ans: To enable auto-completion, you'll need to install the Playwright extension in your code editor (VS Code)
      2) Can you show how can we use import statements inside POM, the code is only working if I use require not import
      Ans: Playwright uses Node.js, and in Node.js, the require statement is used to include modules. The equivalent of import in Node.js is require.
      It's not possible to use the import statement in Playwright POM files as it is part of ES6 and not supported by Node.js.
      In Playwright, you can use the require statement to import modules in POM (Pages Object Model) files
      /*
      const playwright = require('playwright');
      (async () => {
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.goto('example.com');
      // your code here
      await browser.close();
      })();
      */
      3) lf i use expect inside the pom i am getting error as below, the browser is closed immediatley its not waiting 30 seconds
      Ans: It seems that the locator that you're trying to use in your expect statement is not available because the browser has already been closed. To resolve this issue, you'll need to wrap your expect statement in a try-catch block and catch any exceptions that might be thrown.
      eg:
      try {
      await locator.fill('input text');
      await expect(locator).toFill('input text');
      } catch (error) {
      console.error(error);
      }

  • @amulyasree09
    @amulyasree09 Год назад

    Very helpful!! Could you pls cover sessions on Visual Testing, Data driven(Parameterization), API test with an example. Thank you so much!!

  • @АртемийТемник
    @АртемийТемник Год назад

    Great thanks for your course, it was wonderful!

    • @RaghavPal
      @RaghavPal  Год назад

      You're very welcome Артемий

  • @harishmca
    @harishmca Год назад

    I am using ts file , but could not run the test file using npx playwright test

    • @RaghavPal
      @RaghavPal  Год назад

      Harish
      To run a TypeScript test file with Playwright Test, you need to install the `ts-node` package. This package will transpile your TypeScript code to JavaScript before Playwright Test runs it.
      To install `ts-node`, run the following command:
      ```
      npm install ts-node
      ```
      Once `ts-node` is installed, you can run your TypeScript test file with Playwright Test by using the following command:
      ```
      npx ts-node tests/my-test.spec.ts
      ```
      If you want to run all of your TypeScript test files, you can use the following command:
      ```
      npx ts-node tests/*.spec.ts
      ```
      If you are using a test runner like Jest or Mocha, you can configure them to use `ts-node` to transpile your TypeScript code.
      Here is an example of how to configure Jest to use `ts-node`:
      ```
      // jest.config.js
      module.exports = {
      transform: {
      '^.+\\.tsx?$': 'ts-jest',
      },
      };
      ```
      Once you have configured your test runner to use `ts-node`, you will be able to run your TypeScript test files with Playwright Test without any problems.

    • @harishmca
      @harishmca Год назад

      @@RaghavPal Thanks for the update. I did not use ts-node package , the problem was test('test') property was not defined next to the ts file name

  • @HybridFox_Ava
    @HybridFox_Ava Год назад

    Hi, Can I ask how to handle Your connection is not private in the browser?

    • @RaghavPal
      @RaghavPal  Год назад

      Yes, Playwright provides several ways to handle the "Your connection is not private" error in the browser:
      **1. Ignore HTTPS errors:** You can configure Playwright to ignore HTTPS errors during browser launch. This will bypass the security warning and allow you to proceed with your automation.
      ```python
      from playwright.chromium import playwright
      launch_options = {
      "ignoreHTTPSErrors": True,
      }
      with playwright.chromium.launch(options=launch_options) as browser:
      # Your automation script here
      ...
      ```
      **2. Accept insecure certificates:** You can instruct Playwright to accept insecure certificates. This option is less secure than ignoring errors but might be necessary for some self-signed certificates.
      ```python
      from playwright.chromium import playwright
      launch_options = {
      "acceptInsecureCerts": True,
      }
      with playwright.chromium.launch(options=launch_options) as browser:
      # Your automation script here
      ...
      ```
      **3. Use a custom CA certificate:** If you have a trusted CA certificate for the website, you can specify it during browser launch. This ensures a secure connection while bypassing the default browser warning.
      ```python
      from playwright.chromium import playwright
      ca_cert_path = "path/to/your/ca.pem"
      launch_options = {
      "args": [f"--ignore-certificate-errors-spki-list={ca_cert_path}"],
      }
      with playwright.chromium.launch(options=launch_options) as browser:
      # Your automation script here
      ...
      ```
      **4. Fix the underlying issue:** Ideally, you should investigate and address the root cause of the security warning. This may involve installing a valid SSL certificate on the website or updating your browser's trust store.
      Remember, ignoring errors or accepting insecure certificates should only be used as a temporary solution for testing purposes. For production-grade automation, ensure a secure connection by fixing the underlying issue.
      I hope this helps

  • @professor4738
    @professor4738 Год назад

    when im use playwright for login page module that time pass key step was shows "objec object " issues shows every time came this issues that time incorrectley entered automatically ?

    • @RaghavPal
      @RaghavPal  Год назад +1

      The error message "object object" indicates that Playwright is unable to locate the element that you are trying to interact with. This can happen for a few reasons:
      * The element may not be present on the page.
      * The element may be hidden or obscured by another element.
      * The element may have a different ID or CSS selector than the one that you are using.
      * There may be a bug in the Playwright code.
      To troubleshoot this issue, you can try the following:
      * Make sure that the element is present on the page and that it is visible.
      * Try using a different ID or CSS selector to locate the element.
      * Try rerunning the test.
      * If you are still getting the error, you can try searching for help online. There are many resources available online that can help you to troubleshoot Playwright problems.
      Here are some additional tips for using Playwright to interact with login page modules:
      * Make sure that you are using the correct ID or CSS selector to locate the username and password fields.
      * Use the `type()` method to enter the username and password into the fields.
      * Use the `click()` method to click the login button.
      * Use the `waitForNavigation()` method to wait for the page to navigate to the next page after the user has logged in.
      If you are still having problems using Playwright to interact with login page modules, you can try using a different automation framework, such as Selenium.
      Here are some additional tips for troubleshooting Playwright problems:
      * Run the Playwright test runner in debug mode. To do this, run the following command:
      ```
      npx playwright test --debug
      ```
      This will print out more detailed information about what the Playwright test runner is doing, which may help you to identify the problem.
      * Search for help online. There are many resources available online that can help you to troubleshoot Playwright problems.
      I hope this helps!

    • @professor4738
      @professor4738 Год назад

      @@RaghavPal thanks lot man its worked 😍😍👌👌🤝

  • @NatachaHarivelomandimby-h1w
    @NatachaHarivelomandimby-h1w Год назад

    Hello! Thanks for the video. I want to get my project's page loading time. Do you have videos that can explain playwright page load time?

    • @RaghavPal
      @RaghavPal  Год назад

      Natacha
      To get your project's page loading time in Playwright, you can use the `page.timings()` method. The `page.timings()` method returns an object that contains information about the page's loading time, including the following:
      * **domContentLoaded:** The time at which the document's content was loaded.
      * **load:** The time at which the page was loaded.
      * **networkTime:** The time it took to download the page's resources.
      * **renderTime:** The time it took to render the page.
      To get the page loading time, you can use the `load` property of the `timings` object. For example, the following code will get the page loading time for the URL `www.google.com`:
      ```
      import playwright from 'playwright';
      (async () => {
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.goto('www.google.com');
      const timings = await page.timings();
      const loadTime = timings.load;
      console.log('Page load time:', loadTime);
      await browser.close();
      })();
      ```
      This code will print the page loading time to the console.
      I hope this helps

    • @NatachaHarivelomandimby-h1w
      @NatachaHarivelomandimby-h1w Год назад

      @@RaghavPal Thank you for this explanation. It's clear.

  • @shubhambasalwar980
    @shubhambasalwar980 Год назад

    Hi Raghav,
    I am following POM by watching this video since long. I am facing an issue when working with two tabs.
    After clciking on an Web element new tab is getting opened and i have to validate few things on new page. I am trying with a single constructor(page), i think the error is due to the fixture "page" bcz by using page fixtures its unable to perform an action on child window. It would be great if you can help me out.
    Awaiting for your reply.
    Thanks in advance.

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Shubham
      To handle a new tab or window that opens after clicking on a web element in Playwright, you need to switch the focus to the new page. By default, Playwright operates on the active page in the current context. Here's how you can handle this situation:
      1. After clicking on the web element, you can use the `page.waitForEvent('popup')` method to wait for the new page to open. It returns a promise that resolves to the new page instance.
      2. Once the new page is opened, you can assign it to a variable and then perform actions on that page. For example:
      ```javascript
      const newPage = await context.waitForEvent('page');
      await newPage.waitForLoadState(); // Wait for the new page to load
      // Perform actions on the new page
      await newPage.click('.selector');
      await newPage.fill('#input', 'text');
      // Switch back to the original page
      await page.bringToFront();
      ```
      In this example, `context` refers to the browser context, and `page` refers to the original page where you clicked on the web element.
      By using this approach, you can switch the focus between the original page and the new page to perform actions and validations as needed.
      Note: Make sure to handle any asynchronous behavior, such as waiting for the new page to load, before interacting with elements on the new page.

  • @ucanhle4000
    @ucanhle4000 Год назад

    super easy very clear cryy thank you

  • @shikhashukla8060
    @shikhashukla8060 9 месяцев назад

    Hi Raghav
    Thanks you so much for providing such knowledgeful and informative sessions. I do have few Queries :
    IN POM object model
    I want to handle a scenario where i am clicking on link and popup is coming and i want to handle that logic in page only
    when i am trying to use code
    if(page.locator('div').isvisible()){
    await page.locator('div').filter({ hasText: /^360 Code$/ }).click();
    await page.getByRole('button', { name: 'OK', exact: true }).click();
    }

    I am getting error ReferenceError: page is not defined (Although i imported :import { Page } from "@playwright/test" )
    Also can you explain how can we write methods in POM pages for window popup and entering data into it and call that method from Test case .
    Thanking you in Advance

    • @RaghavPal
      @RaghavPal  9 месяцев назад

      Shikha
      Certainly! Let's address your queries step by step:
      1. Handling Popups in Page Object Model (POM):
      - To handle a scenario where clicking on a link opens a popup, you can encapsulate the logic within your page object class.
      - First, create a method in your page object class that clicks the link and handles the popup.
      - Then, call this method from your test case.
      2. Error: ReferenceError: page is not defined:
      - The error occurs because the variable `page` is not defined in the scope where you're trying to use it.
      - To resolve this, make sure you pass the `page` object to your page object class during initialization.
      - Here's an example of how you can structure your code:
      ```javascript
      // Your page object class (e.g., MyPage.ts)
      import { Page } from '@playwright/test';
      export class MyPage {
      private page: Page;
      constructor(page: Page) {
      this.page = page;
      }
      async clickLinkAndHandlePopup() {
      await this.page.locator('div').filter({ hasText: /^360 Code$/ }).click();
      await this.page.getByRole('button', { name: 'OK', exact: true }).click();
      }
      }
      // In your test case
      import { test, expect } from '@playwright/test';
      import { MyPage } from './MyPage'; // Adjust the path to your page object class
      test('Handle popup after clicking link', async ({ page }) => {
      const myPage = new MyPage(page);
      await myPage.clickLinkAndHandlePopup();
      // Add assertions or further actions as needed
      });
      ```
      3. Writing Methods for Window Popups:
      - In your page object class, create a method that clicks the link (which opens the popup) and handles the popup.
      - For entering data into the popup, create another method that interacts with the popup elements (e.g., filling input fields).
      - Call these methods from your test case as needed.
      Remember to adjust the code snippets above to match your actual page object class and test case. The key is to encapsulate the logic related to the popup within your page object class to keep your test scripts clean and maintainable.
      ..

    • @shikhashukla8060
      @shikhashukla8060 9 месяцев назад

      @@RaghavPal Thank alot I will try this out

  • @mihaelacostea5783
    @mihaelacostea5783 Год назад

    Did you happen to have this error thrown when running a test? "400. That’s an error.
    The server cannot process the request because it is malformed. It should not be retried. That’s all we know." I keep getting it and can't get past it.

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Mihaela
      The error message you're seeing indicates that there is an issue with the request that's being sent to the server. It's possible that there's an issue with the request payload, headers, or URL being used by Playwright.
      Here are some steps you can take to try to resolve the issue:
      Check the URL: Make sure that the URL being used in the request is correct and valid.
      Check the request payload: If the request requires a payload, make sure that it's formatted correctly and contains all the necessary information.
      Check the request headers: Make sure that the headers being used in the request are correct and valid.
      Try a different endpoint: If the issue persists, try using a different endpoint to see if the issue is specific to the endpoint being used.
      Check the server logs: If the issue persists, check the server logs to see if there are any errors or warnings that might help identify the issue.
      Try using a different browser: If the issue persists, try using a different browser to see if the issue is specific to the browser being used.
      If none of these steps resolve the issue, you may want to try reaching out to the Playwright community or support team for further assistance.

  • @natalyaluhovska9641
    @natalyaluhovska9641 8 месяцев назад

    Hi @Raghav
    Thank you very much for the video.
    In the video you created 1 single function for 3 actions, but, you mentioned it is possible to create separate atomic functions. Can you show an example how to create a separate functions for all three actions?

    • @RaghavPal
      @RaghavPal  8 месяцев назад +1

      Natalya
      In the video, we demonstrated a single function that combined three actions. However, breaking down those actions into separate atomic functions is a great practice, especially when working with the Page Object Model (POM) in Playwright. Let's create separate functions for each action using an example.
      Consider a scenario where we have a web page representing a blog post. We want to perform the following actions:
      1. Navigate to the blog post page.
      2. Click the "Read More" button to expand the full content.
      3. Verify that the expanded content is visible.
      We'll create a Page Object Model class called `BlogPostPage` to encapsulate these actions. Here's how you can structure it:
      ```javascript
      // BlogPostPage.js
      const { expect } = require('@playwright/test');
      class BlogPostPage {
      constructor(page) {
      this.page = page;
      this.readMoreButton = page.locator('button', { text: 'Read More' });
      this.expandedContent = page.locator('.expanded-content');
      }
      async navigateToBlogPost() {
      // Implement navigation logic here (e.g., go to a specific URL)
      // For simplicity, let's assume the page is already open.
      }
      async clickReadMoreButton() {
      await this.readMoreButton.click();
      }
      async verifyExpandedContentVisible() {
      await expect(this.expandedContent).toBeVisible();
      }
      }
      module.exports = BlogPostPage;
      ```
      Now let's break down the actions:
      1. `navigateToBlogPost()`:
      - This function handles navigating to the blog post page. You can customize it to load the specific URL or perform any other necessary setup.
      - For simplicity, we assume the page is already open.
      2. `clickReadMoreButton()`:
      - This function clicks the "Read More" button on the page.
      - It's a straightforward action that focuses on a single task.
      3. `verifyExpandedContentVisible()`:
      - This function verifies that the expanded content (e.g., the full blog post) is visible.
      - We use Playwright's `expect` assertion to check if the element is visible.
      Now, when you use the `BlogPostPage` class in your test scripts, you can call these functions separately:
      ```javascript
      // Your test script
      const { test, expect } = require('@playwright/test');
      const BlogPostPage = require('./BlogPostPage'); // Import your Page Object Model
      test('Verify expanded content on blog post page', async ({ page }) => {
      const blogPostPage = new BlogPostPage(page);
      await blogPostPage.navigateToBlogPost();
      await blogPostPage.clickReadMoreButton();
      await blogPostPage.verifyExpandedContentVisible();
      });
      ```
      By organizing your actions into separate functions, you achieve better readability, maintainability, and reusability.
      Each function focuses on a specific task, making your test scripts more robust and easier to manage

    • @natalyaluhovska9641
      @natalyaluhovska9641 8 месяцев назад

      @@RaghavPal Thank you very much for your help. I love your videos, perfect explanation, excellent English, and friendly attitude to your subscribers! That encourages us never to stop learning👌

  • @zorrySerafimova
    @zorrySerafimova Год назад

    run the npm init playwright@latest command in VS code but it didn't ask me if I wanted to u see Typescript vs Javascript. Is it as simple as switching the .ts to .js in order to use javascript?

    • @RaghavPal
      @RaghavPal  Год назад +1

      Yes, it is as simple as switching the .ts to .js in order to use JavaScript. By default, Playwright uses TypeScript, but you can also use JavaScript by changing the file extension.
      For example, if you have a file called `my_script.ts`, you can change it to `my_script.js` and it will still work with Playwright.
      However, there are some benefits to using TypeScript with Playwright. TypeScript is a typed language, which means that it can help you to catch errors at compile time. This can help you to write more reliable code.
      If you are not familiar with TypeScript, you can learn more about it here: www.typescriptlang.org/
      Here are some additional things to keep in mind when using JavaScript with Playwright:
      * You need to install the `@playwright/test-javascript` package.
      * You need to use the `playwright.test.js` file as the entry point for your tests.
      * You need to use the `playwright.test.assert` function to make assertions in your tests.

  • @Snehaandsahasra
    @Snehaandsahasra Год назад

    Sir. How much JavaScript knowledge will be needed for playwright??

    • @RaghavPal
      @RaghavPal  Год назад

      The amount of JavaScript knowledge you need for Playwright depends on your desired level of interaction and automation complexity. Here's a breakdown:
      *Basic Automation:*
      * For basic automation tasks like clicking buttons, entering text, and submitting forms, you don't need extensive JavaScript knowledge. Playwright provides a high-level API that allows you to perform these actions without writing JavaScript directly.
      * Familiarity with basic JavaScript syntax and data structures like arrays and objects will be helpful for understanding Playwright's API and writing simple scripts.
      *Advanced Automation:*
      * For more complex automation scenarios like interacting with dynamic content, scraping data, and handling JavaScript errors, you'll need a good understanding of JavaScript. This includes:
      * DOM manipulation: Understanding how to access and manipulate elements in the DOM using JavaScript methods like `document.querySelector`, `getElementBy*`, and `click`.
      * Asynchronous programming: Understanding how to use asynchronous functions like `Promise` and `async/await` to handle asynchronous operations in your scripts.
      * Event handling: Understanding how to listen for and respond to events like `click`, `change`, and `scroll` using JavaScript event listeners.
      *JavaScript for Customization:*
      * If you need to extend Playwright's functionality or create custom scripts, you'll need a strong foundation in JavaScript. This includes:
      * Object-oriented programming: Understanding how to define classes, objects, and methods in JavaScript.
      * Functional programming: Understanding how to use functions as first-class citizens and write functional code.
      * Advanced JavaScript features: Understanding features like closures, modules, and generators can be beneficial for writing complex and reusable scripts.
      While you can start using Playwright with basic JavaScript knowledge, continuously improving your JavaScript skills will unlock more advanced automation possibilities and make you more efficient in writing robust and maintainable scripts.
      Here are some resources for learning JavaScript:
      *Online courses:* Platforms like Codecademy, FreeCodeCamp, and Coursera offer interactive courses for learning JavaScript.
      *Books:* "Eloquent JavaScript" by Marijn Haverbeke is a popular book for learning JavaScript fundamentals.
      *Documentation:* The official JavaScript documentation provides comprehensive information on the language features and syntax.
      *Playwright documentation:* Playwright's own documentation includes examples and best practices for using JavaScript with Playwright.
      Remember, the level of JavaScript knowledge you need depends on your specific automation goals. Start with the basics and gradually progress to more advanced topics as your needs and skills evolve.

    • @Snehaandsahasra
      @Snehaandsahasra Год назад

      Thank you very much for the detailed information Sir👍. I will take your advise and start from basics and go to advanced as needed.

  • @softwaretestinglearninghub
    @softwaretestinglearninghub Год назад

    It is a great detailed video, thank you!

  • @satyadurgadeviv503
    @satyadurgadeviv503 Год назад

    Hi Raghav! Will be there any session on Playwright API testing?
    I started doing api testing but I have doubt, not sure whom to ask and where

    • @RaghavPal
      @RaghavPal  Год назад

      I will plan on this, you can ask your doubt here

    • @satyadurgadeviv503
      @satyadurgadeviv503 Год назад

      @@RaghavPal thank you so much, i am sending get request where I get response, the problem is I want to get the count of items in the json . For example if get request for users will give response of all the users but how to know the number of users?

    • @RaghavPal
      @RaghavPal  Год назад

      Satya
      In Playwright, you can extract the count of items in a JSON response by parsing the response body and accessing the relevant JSON property. Here's an example of how you can achieve this:
      ```javascript
      const { chromium } = require('playwright');
      async function getUserCount() {
      const browser = await chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      // Send the GET request
      const response = await page.goto('api.example.com/users');
      const responseBody = await response.json();
      // Extract the count of users from the JSON response
      const userCount = responseBody.length; // Assuming the JSON response is an array
      // Output the user count
      console.log(`Number of users: ${userCount}`);
      await browser.close();
      }
      getUserCount();
      ```
      In this example, we use Playwright to send a GET request to the URL `'api.example.com/users'`. We then extract the JSON response body using `response.json()`. Assuming the response is an array of users, we can access its length to obtain the count of users.
      Please note that the code snippet assumes a basic setup using Playwright's Chromium browser. You may need to adjust the code to match your specific Playwright configuration and JSON response structure.
      By parsing the JSON response and accessing the length property, you can retrieve the count of items (users in this case) in the JSON response

    • @satyadurgadeviv503
      @satyadurgadeviv503 Год назад

      @@RaghavPal thank you so much for your reply, will definitely try and let you know

    • @satyadurgadeviv503
      @satyadurgadeviv503 Год назад

      @@RaghavPal Thank you once again for clear explanation, as you said I had to do some changes to make it work
      (JSON.parse(await response.text())).length

  • @AshokR-k3w
    @AshokR-k3w Год назад

    @RaghavPal really it's a Fantastic job, I have one doubt, in the page object mode, if I want to put an assertion for the or the element 🙏

    • @AshokR-k3w
      @AshokR-k3w Год назад

      await (page.getByText("View All Under 5 Lakh Carss")).isVisible();//View All Under 5 Lakh Cars//
      await expect(page.getByText("View All Under 5 Lakh Cars")).toHaveText('View All Under 5 Lakh Cars');

    • @RaghavPal
      @RaghavPal  Год назад +1

      Ashok
      In Playwright's page object model (POM), you can use assertions to verify the expected behavior of elements. While both approaches you mentioned can work, there are subtle differences and best practices to consider:
      *1. Using `isVisible`:*
      * This method checks if the element is visible on the page. It's a good option for verifying that the element is rendered and not hidden.
      ```javascript
      await expect(page.getByText('View All Under 5 Lakh Cars')).toBeVisible();
      ```
      *2. Using `toHaveText`:*
      * This method checks if the element's text content matches the expected text. It verifies both the visibility and the actual content.
      ```javascript
      await expect(page.getByText('View All Under 5 Lakh Cars')).toHaveText('View All Under 5 Lakh Cars');
      ```
      *Choosing between the two:*
      * If you only need to verify that the element is visible, `isVisible` is sufficient and slightly more efficient.
      * If you need to ensure both visibility and the specific text content, `toHaveText` is the recommended approach.
      * Additionally, `toHaveText` offers additional matchers like `toContain` and `toMatch` for more complex text verification.
      *Best practices:*
      * Use descriptive and meaningful text for both the `getByText` selector and the expected text in the assertion.
      * Group related assertions together for better code readability and maintainability.
      * Consider using `waitForSelector` before the assertion to ensure the element is loaded and available.
      **Here's a breakdown of your example code:**
      ```javascript
      await (page.getByText("View All Under 5 Lakh Carss")).isVisible();//View All Under 5 Lakh Cars//
      await expect(page.getByText("View All Under 5 Lakh Cars")).toHaveText('View All Under 5 Lakh Cars');
      ```
      This code first checks if the element with the text "View All Under 5 Lakh Carss" is visible on the page using `isVisible`. Then, it uses `toHaveText` to assert that the element's text content exactly matches "View All Under 5 Lakh Cars".
      Both approaches verify the element's presence and content, but `toHaveText` provides a more comprehensive assertion and is generally recommended for most cases

    • @AshokR-k3w
      @AshokR-k3w Год назад

      @@@RaghavPal thank you so much for your quick response🙏, it means a lot, I'm implementing in the live project, and I'm stuck in this place thanks a lot now I know how to do it

  • @learnserve
    @learnserve Год назад

    Thanks for the video but where is the verification step that we arrived on the expected page?

    • @RaghavPal
      @RaghavPal  Год назад

      Yes, you can add that, like verifying some element, title, or doing next actions

    • @learnserve
      @learnserve Год назад

      @@RaghavPal I think, each scenario or test should have at least one verification step: without it, how could the purpose of the test be achieved? Just taking some actions then... what? Who knows the last action performed well?

    • @RaghavPal
      @RaghavPal  Год назад

      Yes, it will help and it is standard for automation testing

    • @Snehaandsahasra
      @Snehaandsahasra 10 месяцев назад

      Hi Raghav . I have a scenario.
      In POM, how can we get text of an element from a page class method and return that value to the test and perform assertion in the test. In Playwright documentation and many other training places, they are asserting in the page class . Is this a good practice? @@RaghavPal

    • @RaghavPal
      @RaghavPal  10 месяцев назад +1

      You're right, there are two approaches to assertion in POM (Page Object Model): asserting in the page class or asserting in the test class. Both have their pros and cons, and the best practice depends on your specific situation and preference.
      Asserting in the Page Class:
      Pros:
      Localizes code: Keeps assertions close to the element manipulation logic, making the code more readable and focused.
      Reduces repetition: Avoids repeating assertions in multiple tests for the same element.
      Centralized error reporting: Failures are readily identified within the page class, providing clearer context.
      Cons:
      Increases page class complexity: Can bloat the page class with many assertion statements, potentially affecting maintainability.
      Tight coupling: Ties page classes to specific test logic, making them less reusable across different scenarios.
      Limited visibility: Failures might not be clear in the overall test flow, especially for complex scenarios.
      Asserting in the Test Class:
      Pros:
      Keeps test classes clean: Focuses test classes on test setup and execution, improving readability and separation of concerns.
      Reusability: Assertions can be easily reused across different tests for the same element.
      Holistic view: Failures are reported within the context of the test case, providing a clearer picture of the test flow.
      Cons:
      Duplication: May lead to repetitive code if asserting the same element across multiple tests.
      Less informative: Error messages might be less specific, requiring additional navigation to identify the failing element.
      Reduced locality: Requires jumping between test and page classes to understand element manipulation and assertion logic.
      Best Practice:
      Ultimately, the best practice depends on several factors, including project size, team preference, and complexity of test scenarios.
      Here are some recommendations:
      Simple assertions: Favor asserting in the page class for straightforward checks, improving code readability and localization.
      Complex scenarios: Use assertions in the test class for intricate interactions or multi-step checks, maintaining a clear test flow.
      Reusable assertions: Create utility methods in the page class for commonly used assertions across tests, promoting code reuse.
      Balance complexity: Don't overburden page classes with too many assertions; strive for a balance between locality and readability.
      Remember: Choose the approach that keeps your code clean, readable, and maintainable while providing clear and concise test results. You can even employ a mix of both approaches within your project based on the specific needs of each test case..
      I hope this clarifies the pros and cons of each approach and helps you determine the best practice for your POM implementation

  • @svksuman
    @svksuman Год назад

    Hi Raghav.. it was great and good session.. it would be great if you cover reading data from Excel/CSV...will be waiting for that.

    • @RaghavPal
      @RaghavPal  Год назад

      Thanks Suman, I will plan

  • @АндрейШляхтович
    @АндрейШляхтович 8 месяцев назад

    Thank you very much!
    It's really helpfull

    • @RaghavPal
      @RaghavPal  8 месяцев назад +1

      You are welcome Андрей

  • @pradipvaghela3179
    @pradipvaghela3179 Год назад

    Hey brother can you provide a solution for this error " Browser has been closed at obejct". while runinng a particular code of the module it's working properly. But, while running the whole script it failed and give an error " Browser has been closed at obejct". can you please assist me how to resolve this for my script.🙏

    • @RaghavPal
      @RaghavPal  Год назад

      Pradip
      The error message `Browser has been closed at object` indicates that Playwright is trying to interact with a browser that has already been closed. This can happen for a number of reasons, such as:
      * You are explicitly closing the browser in your code.
      * Another process is closing the browser.
      * The browser crashed.
      * The browser was killed by the operating system.
      To resolve this error, you need to identify the reason why the browser is being closed and take steps to prevent it from happening.
      Here are some things to check:
      *Make sure that you are not explicitly closing the browser in your code.* Playwright will automatically close the browser when your script finishes running.
      *Check for any other processes that may be closing the browser.* For example, if you are running your tests in a CI/CD pipeline, make sure that the pipeline is not killing the browser before your tests have finished running.
      *If you are using a cloud-based browser testing platform, make sure that your browser session is not expiring.* Cloud-based browser testing platforms typically expire browser sessions after a certain period of inactivity.
      Once you have identified the reason why the browser is being closed, you can take steps to prevent it from happening. For example, if you are explicitly closing the browser in your code, you can move the code to the end of your script so that the browser is not closed until your tests have finished running.
      If you are still having problems, you can contact Playwright support for help.
      Here are some additional tips for avoiding `Browser has been closed at object` errors in Playwright:
      * Use a context manager to manage your browser. This will ensure that the browser is always closed properly, even if an exception occurs.
      * Use the `browser.isClosed()` method to check if the browser is closed before interacting with it.
      * Set a timeout for each of your Playwright actions. This will help to prevent your tests from hanging if the browser takes too long to respond.
      I hope this helps

  • @rohitbahadur2504
    @rohitbahadur2504 Год назад

    Big Fan of yours Raghav

  • @SubramanyamPalla
    @SubramanyamPalla 6 месяцев назад

    Hey Raghav,
    Is there a best way to migrate cypress code to playwright ?

    • @RaghavPal
      @RaghavPal  6 месяцев назад

      You can use the following tools to migrate it to Playwright:
      1. [Cypress to Playwright Converter](demo.playwright.dev/cy2pw/):
      - Paste your Cypress code into this tool, and it will generate the equivalent Playwright test cases for you.
      2. [Ray.run's Cypress to Playwright Tool](ray.run/tools/cypress-to-playwright):
      - Similar to the previous tool, this one also converts Cypress code into Playwright code.
      - Simply paste your Cypress code, and you'll receive the corresponding Playwright test cases.
      Remember, these tools make the migration process smoother, allowing you to focus on writing robust end-to-end tests with Playwright
      --

    • @SubramanyamPalla
      @SubramanyamPalla 6 месяцев назад

      @@RaghavPal Thank you for the quick reply, my project contains many files based on pages to copy and paste into to above tools will take at least 3 to 4 days.
      Is there any other way to convert cypress code into Playwright ??

    • @RaghavPal
      @RaghavPal  6 месяцев назад +1

      I understand that manually converting each file can be time-consuming. While the tools I mentioned earlier are helpful for smaller code snippets, let's explore a more efficient approach for migrating your entire project from Cypress to Playwright:
      1. Automated Refactoring:
      - Instead of manually copying and pasting each file, consider using automated refactoring tools. These tools can help you convert your Cypress codebase to Playwright in a more systematic way.
      - Here's a high-level process you can follow:
      a. Backup Your Codebase:
      - Before making any changes, create a backup of your existing Cypress codebase. This ensures that you have a safety net in case anything goes wrong during the migration.
      b. Analyze Dependencies:
      - Identify any Cypress-specific dependencies in your project. These might include Cypress commands, fixtures, and custom utilities.
      - Make a list of these dependencies so you know what needs to be replaced.
      c. Create a Migration Plan:
      - Divide your project into smaller chunks (e.g., files, components, or features).
      - Prioritize the chunks based on critical functionality or test coverage.
      - Create a migration plan that outlines which chunks you'll tackle first.
      d. Write Conversion Scripts:
      - Write custom scripts or use existing tools to automate the conversion process.
      - For example, you can write a script that searches for specific Cypress commands (e.g., `cy.get`, `cy.click`) and replaces them with equivalent Playwright commands (e.g., `page.waitForSelector`, `page.click`).
      - Replace Cypress-specific fixtures and utilities with Playwright equivalents.
      e. Test Incrementally:
      - As you refactor each chunk, run tests incrementally to ensure that functionality remains intact.
      - Fix any issues that arise during testing.
      f. Gradual Migration:
      - Gradually migrate your entire project, chunk by chunk.
      - Monitor test results and address any failures promptly.
      2. Manual Review and Tweaking:
      - Even with automated tools, manual review is essential.
      - Inspect the converted code to ensure correctness and consistency.
      - Address any edge cases or custom Cypress commands that might not have direct Playwright equivalents.
      3. Leverage Community Resources:
      - Join developer forums, communities, or social media groups related to Playwright.
      - Seek advice from others who have migrated from Cypress to Playwright. They might share useful tips, best practices, and gotchas.
      Remember that migrating a large codebase can be a gradual process, so be patient and thorough
      --

  • @sanjeev8720
    @sanjeev8720 Год назад

    Hi Sir.. Can you please explain how to read data from Excel sheet and how to connect with data base by using playwright Java script ..

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Sanjeev
      Here are the steps involved:
      1. Import the `fs` and `xlsx` modules.
      2. Use the `fs` module to read the Excel sheet as a string.
      3. Use the `xlsx` module to parse the Excel sheet string into a JavaScript object.
      4. Loop through the rows of the Excel sheet object and extract the data.
      5. Connect to the database using the `sql` module.
      6. Insert the data from the Excel sheet into the database.
      Here is an example of how to do this:
      ```javascript
      const fs = require('fs');
      const xlsx = require('xlsx');
      const sql = require('sql');
      const excelData = fs.readFileSync('./data.xlsx', 'utf8');
      const sheet = xlsx.parse(excelData);
      for (const row of sheet.data) {
      const data = {
      name: row[0],
      email: row[1],
      phone: row[2],
      };
      // Connect to the database.
      const connection = new sql.Connection({
      host: 'localhost',
      port: 3306,
      user: 'root',
      password: 'password',
      database: 'my_database',
      });
      // Insert the data into the database.
      connection.query('INSERT INTO users (name, email, phone) VALUES (?, ?, ?)', [data.name, data.email, data.phone]);
      }
      ```
      This code will read the data from the Excel sheet `data.xlsx` and insert it into the `users` table in the `my_database` database.
      I hope this helps

  • @naz3a316
    @naz3a316 Год назад

    Hi Mr Raghav, first thank you for your efforts !
    I just finished learning from your other 12 videos in this playlist but this one is new and you haven't talked about this "Class" way in any of the other videos, is it an alternative way?

    • @RaghavPal
      @RaghavPal  Год назад

      Hi, Page Object Model is a general principle, not specific to Playwright and can be implemented in other projects and automation frameworks as well. Check this ruclips.net/video/-0F-YBAQdGE/видео.html

  • @singingbird76
    @singingbird76 Год назад

    Hi Raghav, this series was very useful for me and thank you! Have a question regarding Upload project in GitHub. Does it require to initialize i.e. git init, the project before uploading it?

    • @RaghavPal
      @RaghavPal  Год назад

      Yes, in order to upload a project to GitHub, you need to initialize it as a Git repository first. You can do this by running git init command in your project directory. Once the repository is initialized, you can add files to it, commit changes and then push the code to GitHub using git push command.
      Alternatively, you can create a new repository on GitHub first and then clone it to your local machine using the git clone command. Then, copy your project files into the cloned repository, add and commit changes and push the code to GitHub using git push command.
      In either case, initializing the project as a Git repository is an important step to keep track of changes, collaborate with others, and manage code versions.

    • @singingbird76
      @singingbird76 Год назад

      @@RaghavPal Thank you !!!

  • @alexanderkomanov4151
    @alexanderkomanov4151 Год назад

    Thanks a lot for the content!

    • @RaghavPal
      @RaghavPal  Год назад

      Glad you enjoyed it Alexander

  • @arpittandon09
    @arpittandon09 Год назад

    Hi Raghav. Great video. Can you upload some videos on playwright integration with Jenkins, Docker, Kubernetes, AWS EC2, GCP VM

  • @Vineetkumar-hu2cs
    @Vineetkumar-hu2cs Год назад

    Sir how to pass multiple inputs

    • @RaghavPal
      @RaghavPal  Год назад

      Vineet
      To pass multiple inputs to a Playwright Page Object Model, you can use the following methods:
      1. *Use a constructor:* You can pass multiple inputs to the Page Object Model constructor. For example, the following code shows a Page Object Model for a login page with a username and password input:
      ```javascript
      class LoginPage {
      constructor(username, password) {
      this.usernameInput = username;
      this.passwordInput = password;
      }
      async login() {
      await this.usernameInput.fill(this.username);
      await this.passwordInput.fill(this.password);
      await this.submitButton.click();
      }
      }
      ```
      2. *Use setter methods:* You can also pass multiple inputs to the Page Object Model using setter methods. For example, the following code shows a Page Object Model for a login page with username and password inputs:
      ```javascript
      class LoginPage {
      usernameInput;
      passwordInput;
      setUsername(username) {
      this.usernameInput = username;
      }
      setPassword(password) {
      this.passwordInput = password;
      }
      async login() {
      await this.usernameInput.fill(this.username);
      await this.passwordInput.fill(this.password);
      await this.submitButton.click();
      }
      }
      ```
      3. *Use data tables:* You can also use data tables to pass multiple inputs to the Page Object Model. For example, the following code shows a Page Object Model for a login page with username and password inputs, using a data table:
      ```javascript
      class LoginPage {
      constructor(data) {
      this.usernameInput = data.username;
      this.passwordInput = data.password;
      }
      async login() {
      await this.usernameInput.fill(this.username);
      await this.passwordInput.fill(this.password);
      await this.submitButton.click();
      }
      }
      ```
      Which method you choose to use will depend on your specific needs and preferences.
      Here is an example of how to use a Page Object Model to pass multiple inputs to a login page:
      ```javascript
      // Create a new instance of the LoginPage Page Object Model.
      const loginPage = new LoginPage('my-username', 'my-password');
      // Login to the website.
      await loginPage.login();
      ```
      You can also use data tables to pass multiple inputs to multiple Page Object Models. For example, the following code shows how to pass multiple inputs to a login page and a registration page:
      ```javascript
      // Create a data table with the user credentials.
      const userData = {
      username: 'my-username',
      password: 'my-password',
      };
      // Create new instances of the LoginPage and RegistrationPage Page Object Models.
      const loginPage = new LoginPage(userData);
      const registrationPage = new RegistrationPage(userData);
      // Login to the website and register a new user.
      await loginPage.login();
      await registrationPage.register();
      ```
      By using Page Object Models and data tables, you can easily pass multiple inputs to your Playwright tests. This will make your tests more reusable and maintainable.

  • @AshokR-k3w
    @AshokR-k3w Год назад

    @RaghavPal, This is my sincere request please do one video verifying all the links on a page using Playwright with JavaScript, I hope you will do it , Thank you so much for your time and effort incredibly good tutorials. Thanks again.

  • @vaishusep18
    @vaishusep18 7 месяцев назад

    Hi Raghav. Can we have codes for little advanced Page Object Model using Playwright and javacript. I mean keeping all browers and credentials in config files. Also please make video on Data driven testing using Playwright.
    Thanks

    • @RaghavPal
      @RaghavPal  7 месяцев назад

      I will check and plan on this Rekha

  • @santoshpallerla
    @santoshpallerla Год назад

    Hi Raghav, I am currently working on playwright. I am struggling to implement the web table automation which is developed with react. Our application uses css styling. Can you please do a session on how to implement table automation in playwright using javascript with css selectors. Thanks alot for all your support and efforts to the community

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Santosh, sure, I will plan on this, do you have any demo website where this can be demoed?
      You can use Playwright's built-in page.evaluate() method to execute JavaScript code: This method allows you to execute JavaScript code within the context of the web page, which can be useful for interacting with elements in a table that may not be easily accessible through traditional web automation methods

    • @santoshpallerla
      @santoshpallerla Год назад

      @@RaghavPal I can demo but it violates our company policy

    • @RaghavPal
      @RaghavPal  Год назад

      ok np, in case you find an example on a public demo site, can let me know

    • @pravithvikram
      @pravithvikram Год назад

      Hi santhosh gud evng
      Am working Playwright with js bdd framework
      Am unable to navigate feature file to step defination .which plug in needed could you pls help on this

    • @santoshpallerla
      @santoshpallerla Год назад

      @@pravithvikram I don’t use bdd vikram. I am using in a plain fashion

  • @maheshg1129
    @maheshg1129 Год назад

    Nice Job Sir, can you please make video on Playwright Framework

    • @RaghavPal
      @RaghavPal  Год назад

      Sure Mahesh, can check existing Playwright videos here - automationstepbystep.com/

  • @sarikac316
    @sarikac316 Год назад

    Hi Sir, thanks for the suggestions. I am having 7yrs exp in manual testing and now i am currently in career gap of almost 4 yrs due to personal reasons. Now i am interested to restart my career in testing itself.. but i am not interested to move on to automation side. so what role would be fit for me to restart my career... pls reply sir...

    • @RaghavPal
      @RaghavPal  Год назад

      Hi Sarika, can check the following options:
      Manual Test Engineer
      Test Analyst
      Test Lead
      Test Manager
      Test Consultant

    • @pravithvikram
      @pravithvikram Год назад

      If u possible do the video on Bdd cucumber playwright with js
      Am working on that actually am new for playwright with js .. previously I have worked on selenium with Java Bdd cucumber
      If provide online classes on that am enthusiastic for learning bdd cucumber Playwright with js

    • @RaghavPal
      @RaghavPal  Год назад +1

      I will check and plan Vikram

    • @pravithvikram
      @pravithvikram Год назад

      @@RaghavPal in vs code bdd cucumber Playwright with js
      Am unable to navigate feature file to step defination which plug in needed could you please help on this

    • @pravithvikram
      @pravithvikram Год назад

      @@RaghavPal could provide online classes on playwright with js on bdd framework

  • @vadymtsys8907
    @vadymtsys8907 Год назад

    thanks!

  • @valentinevdokimov4002
    @valentinevdokimov4002 Год назад

    API testing Required.)))

    • @RaghavPal
      @RaghavPal  Год назад

      will do Valentin

    • @praveen98100
      @praveen98100 Год назад

      Getting No tests found error in the terminal when I am using the command npx playwright test... Rest all I am following all the steps you said

  • @johngill9648
    @johngill9648 Год назад

    too much bloat, cut it down

  • @HassanNaveed-c5s
    @HassanNaveed-c5s Год назад

    how can I integrate it in my ci/cd pipeline before deploying my product on the QA/Dev Servers on successful execution of test cases?

    • @RaghavPal
      @RaghavPal  Год назад

      Hassan
      To integrate Playwright in your CI/CD pipeline before deploying your product on the QA/Dev Servers on successful execution of test cases, you can follow these steps:
      1. Install Playwright in your CI/CD environment. You can do this by running the following command:
      ```
      npm install -g playwright
      ```
      2. Create a Playwright test script. This script should define the tests that you want to run. For example, the following script tests the login functionality of a website:
      ```
      const { chromium } = require('playwright');
      (async () => {
      const browser = await chromium.launch();
      const page = await browser.newPage();
      await page.goto('example.com/login');
      await page.fill('input[name="username"]', 'username');
      await page.fill('input[name="password"]', 'password');
      await page.click('button[type="submit"]');
      const isLoggedIn = await page.evaluate(() => document.querySelector('.is-logged-in'));
      assert(isLoggedIn);
      await browser.close();
      })();
      ```
      3. Create a CI/CD pipeline that runs the Playwright test script. The pipeline should be configured to run the test script every time there is a new commit to the code repository. If the test script passes, the pipeline should deploy the product to the QA/Dev Servers.
      Here is an example of a CI/CD pipeline that uses GitHub Actions to run Playwright tests and deploy the product to the QA/Dev Servers:
      ```
      name: Playwright Tests
      on:
      push:
      branches:
      - main
      jobs:
      playwright:
      runs-on: ubuntu-latest
      steps:
      - uses: actions/checkout@v2
      - name: Install Playwright
      run: npm install -g playwright
      - name: Run Playwright Tests
      run: playwright test .
      - name: Deploy to QA/Dev Servers
      run: |
      echo "Deploying to QA/Dev Servers..."
      # Your deployment script here
      ```
      This pipeline will run the Playwright test script every time there is a new commit to the main branch of the code repository. If the test script passes, the pipeline will deploy the product to the QA/Dev Servers.
      I hope this helps