Playwright Beginner Tutorial 8 | Demo Login Test

แชร์
ฝัง
  • เผยแพร่เมื่อ 25 ธ.ค. 2024

ความคิดเห็น • 92

  • @jahnavijammi8464
    @jahnavijammi8464 3 หลายเดือนก่อน +1

    Thanks for your detailed videos, they are very useful for beginners. Can you suggest a way to ignore ssl cerificate errors, this pop up is not even recognized by the PlayWright Object locator to cancel them.
    Appreciate your help!

    • @RaghavPal
      @RaghavPal  3 หลายเดือนก่อน

      Jahnavi
      Sometimes those SSL certificate pop-ups get in the way, and Playwright's locators can't even see them. Here are a couple of ways to tell Playwright to just ignore them:
      1. Tell Playwright to Ignore Them from the Start
      When you're setting up your browser, just add this little bit:
      JavaScript
      const context = await browser.newContext({
      ignoreHTTPSErrors: true
      });
      Use code with caution.
      This basically says, "Hey Playwright, don't worry about those SSL errors, just keep going!"
      2. Handle Each Request Individually
      If you want more control, you can tell Playwright to ignore SSL errors on a case-by-case basis:
      JavaScript
      page.on('request', (request) => {
      request.continue({
      overrides: { certificateErrors: 'ignore' }
      });
      });
      This way, you can decide which requests to let through even if they have SSL issues.
      Tip: If you're dealing with self-signed certificates or something similar, you might need to create your own custom CA certificate and add it to your browser's trusted list. But that's a bit more advanced - these two methods should work for most cases
      Let me know if it worked
      -

  • @barkaaymen6619
    @barkaaymen6619 ปีที่แล้ว +2

    thank's for all this videos, i have a question for the 3 examples when i use playwright inspector like you , i got always getBy.. as result , i never got .locator('input[name="Email"]'for example and also i dont have explore , ihave pick locator any help to resolve this for locators?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      Hi Barka
      The difference between `getBy` and `locator` is that `getBy` is a method that takes a selector as its argument and returns a promise that resolves to an element or an array of elements that match the selector. `locator`, on the other hand, is a function that takes a selector as its argument and returns a string that can be used to find the element or elements that match the selector.
      The reason why you are always getting `getBy` as a result when you use the Playwright inspector is because the inspector is using the `getBy` method to find the elements that you select. This is because the `getBy` method is more efficient than the `locator` function.
      The reason why you do not have the `explore` button is because you are using the Playwright inspector in a headless browser. The `explore` button is only available when you are using the Playwright inspector in a browser with a graphical user interface.
      To resolve this issue, you can use the `locator` function to find the elements that you want to interact with. For example, the following code will find the element with the `name` attribute equal to `Email`:
      ```
      const locator = playwright.locator('input[name="Email"]');
      const element = await locator.click();
      ```
      You can also use the `locator` function to find multiple elements. For example, the following code will find all of the elements with the `class` attribute equal to `button`:
      ```
      const locator = playwright.locator('.button');
      const elements = await locator.all();
      ```
      I hope this helps!

  • @sakshamsingh8644
    @sakshamsingh8644 7 หลายเดือนก่อน +1

    Thanks very good explanation with documents

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน

      You are welcome Saksham

  • @szebasztianturbucz308
    @szebasztianturbucz308 7 หลายเดือนก่อน +1

    What would you recommend for someone who learned manual software testing and now wants to learn test automation? I haven't found many guides to learning how to automate apart from bootcamps that cost a fortune.

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน +1

      You can decide on the topics or can check from here - automationstepbystep.com/ and start learning by following with handson

    • @szebasztianturbucz308
      @szebasztianturbucz308 7 หลายเดือนก่อน

      @@RaghavPal Thank you for your answer!

  • @srinathmohan615
    @srinathmohan615 ปีที่แล้ว +1

    Is there any configuration for generating comments while using code recorder, because for me the recorded scripts does have comments generated and certain other assertions are wait like the one yours have generated (For example waitforurl)

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      Hi Srinath,
      Yes, you can configure Playwright's code generator to include comments in the generated code. By default, comments are not included in the generated code, but you can enable them by setting the outputComments option to true when running the npx playwright codegen command.
      For example, to generate code with comments and wait for a specific URL, you can use the following command:
      npx playwright codegen --outputComments --waitForUrl "example.com"
      This will generate code with comments explaining what each line of code does and also include a wait statement for the specified URL.
      You can also customize the format of the generated comments using the commentType and indentType options. For example, to use block-style comments and a tab for indentation, you can use the following command:
      npx playwright codegen --outputComments --commentType "block" --indentType "tab" --waitForUrl "example.com"
      This will generate code with comments formatted in a block-style and indented using tabs.
      I hope this helps you generate code with comments and the necessary assertions.

  • @LavanyaU-zg4jq
    @LavanyaU-zg4jq 7 หลายเดือนก่อน

    Thank you for doing these videos. I have a question - when I run the test if it fails it is generating report and in the report is shows in which step it failed. But it is not saying what is the issue (like the element not found or cannot e.t.c). Is there a way where I can see what is the error and change the script accordingly?

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน +1

      Chinni
      When Playwright generates a test report, it provides information about the failing step, but it doesn't always include detailed error messages by default. However, you can enhance your test scripts to capture more context and specific error details. Here are some strategies to achieve that:
      1. Custom Error Messages:
      - In your test script, add custom error messages using `console.error()` or similar methods. For example:
      ```javascript
      try {
      await page.click('#myButton');
      } catch (error) {
      console.error('Error clicking the button:', error.message);
      }
      ```
      - By adding descriptive messages, you'll know exactly which step failed and why.
      2. Capture Screenshots or Videos:
      - When a test step fails, take a screenshot or record a video to capture the state of the page at that moment. Playwright provides methods for this:
      ```javascript
      await page.screenshot({ path: 'failure-screenshot.png' });
      // or
      await page.video().stop();
      ```
      - Include these screenshots or videos in your test report. They can help you diagnose issues visually.
      3. Verbose Logging:
      - Enable verbose logging during test execution. This can provide additional details about what Playwright is doing behind the scenes.
      - Set the `DEBUG` environment variable to `pw:api` before running your tests:
      ```
      DEBUG=pw:api node your_test_script.js
      ```
      - Check the console output for detailed logs
      4. Handle Errors Explicitly:
      - Instead of relying solely on Playwright's default error handling, catch specific errors and handle them explicitly. For example:
      ```javascript
      try {
      await page.click('#myButton');
      } catch (error) {
      if (error.name === 'TimeoutError') {
      console.error('Button click timed out.');
      } else {
      console.error('Unexpected error:', error.message);
      }
      }
      ```
      5. Inspect Network Requests:
      - Use Playwright's network interception capabilities to inspect network requests and responses. This can help identify issues related to API calls or missing resources.
      - For example:
      ```javascript
      page.route('/*', (route) => {
      console.log('Request intercepted:', route.request().url());
      route.continue();
      });
      ```
      6. Debugging Mode:
      - Run your tests in debugging mode (`headless: false`) to interactively inspect the page when a failure occurs.
      - Add breakpoints using `page.pause()` to pause execution and explore the page state.
      Remember that Playwright provides flexibility, so you can tailor your error handling and reporting based on your specific needs. By combining custom messages, screenshots, and detailed logging, you'll have a clearer understanding of what went wrong during test execution
      --

  • @hovhannesmatevosyan8692
    @hovhannesmatevosyan8692 2 ปีที่แล้ว

    Thanks for the tutorial. Could you please tell how to set values to hidden(input[type=hidden]) input in the form?

    • @RaghavPal
      @RaghavPal  2 ปีที่แล้ว

      can check the method details here www.javadoc.io/doc/com.microsoft.playwright/playwright/latest/com/microsoft/playwright/Page.WaitForSelectorOptions.html

  • @linuvj1241
    @linuvj1241 2 หลายเดือนก่อน

    Hi, thanks for sharing the wonderful session. Request you kindly help me in resolving the below error.
    Error: No tests found.
    Make sure that arguments are regular expressions matching test files.
    You may need to escape symbols like "$" or "*" and quote the arguments.

    • @RaghavPal
      @RaghavPal  2 หลายเดือนก่อน

      "No tests found" usually means Playwright isn't able to locate any test files based on the arguments you provided.
      What is the command you are running. Check the path of the test file in the command. Try to give single forward slashes / in the path and try again..
      If that does not solve try these:
      1. **Check Your Test File Names:** Make sure your test files have the correct file extension. Playwright typically looks for files ending with `.test.js` or `.spec.js`.
      2. **Verify Your Test File Location:** Double-check that your test files are located in the directory you're specifying when you run Playwright.
      3. **Escape Special Characters:** If your test file names or directory paths contain special characters like `$` or `*`, make sure to escape them using a backslash (`\`) before them.
      4. **Quote Your Arguments:** If your arguments contain spaces or other special characters, try enclosing them in single or double quotes.
      Here's an example of how you might run Playwright with escaped characters and quoted arguments:
      ```bash
      npx playwright test 'my-tests/test-file-with-\$.test.js'
      ```
      -

  • @sirishapochiraju3551
    @sirishapochiraju3551 ปีที่แล้ว +1

    Hi Raghav, Thanks for showing the Valid Login tests in Playwright. How to do a Invalid Login test?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Hi Sirisha
      To perform an Invalid Login test in Playwright, you can follow these steps:
      Launch the browser using Playwright
      const { chromium } = require('playwright');
      const browser = await chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      Navigate to the login page of your application.
      await page.goto('yourapplication.com/login');
      Enter invalid login credentials and submit the form.
      await page.fill('#username', 'invalidusername');
      await page.fill('#password', 'invalidpassword');
      await page.click('#submit-button');
      Verify that the login was unsuccessful by checking for an error message
      const errorMessage = await page.textContent('.error-message');
      expect(errorMessage).toBe('Invalid username or password');
      Close the browser
      await browser.close();
      You can customize the above code to suit your specific application and login form

    • @sirishapochiraju3551
      @sirishapochiraju3551 ปีที่แล้ว

      Thanks raghav

  • @ingriddbrito4003
    @ingriddbrito4003 3 หลายเดือนก่อน

    @raghavPal my inspector always closes after a few seconds, even when I am recording the actions.

    • @RaghavPal
      @RaghavPal  3 หลายเดือนก่อน

      From what I've gathered, this issue might be related to the timeout setting in Playwright. By default, the Inspector has a timeout of 30 seconds. If you're not interacting with the Inspector within that timeframe, it will automatically close
      To resolve this, you can try increasing the timeout value when launching the Inspector. For example, you can set it to a higher value like 300 seconds (5 minutes) using the following code:
      Python
      import playwright
      playwright.chromium.launch(headless=False, timeout=300000)
      JS
      const playwright = require('playwright');
      (async () => {
      const browser = await playwright.chromium.launch({ headless: false, timeout: 300000 });
      // ...
      })();
      -

  • @venkateshwarraoch3349
    @venkateshwarraoch3349 7 หลายเดือนก่อน

    In the inspector, Page/test is terminating automatically when the cursor clicking on Click(). any reason?

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน

      Venkat
      Here are some possible reasons and solutions:
      1. Auto-Waiting in Playwright:
      - Playwright indeed has built-in auto-waiting, which means it automatically waits for elements to become ready before performing actions like clicks.
      - However, there are scenarios where this auto-waiting might not work as expected, leading to flaky behavior.
      2. Debugging Steps:
      - To address this issue, follow these steps:
      a. Check Element Availability:
      - Ensure that the element you're trying to click is available in the DOM at the time of execution.
      - If the element is dynamically loaded (e.g., via JavaScript), make sure Playwright waits for it to appear.
      - You can use `page.waitForSelector(selector)` to wait for an element to be present before interacting with it.
      b. Explicitly Wait for Element Clickability:
      - Sometimes auto-waiting might not be sufficient. Explicitly wait for the element to be clickable:
      ```javascript
      await page.click('button', { timeout: 5000 }); // Adjust the timeout as needed
      ```
      c. Inspect Console Errors:
      - Open the browser's Developer Tools (usually by pressing F12) and check the console for any errors.
      - Sometimes JavaScript errors can cause unexpected behavior.
      d. Handle Dialogs:
      - By default, Playwright auto-dismisses dialogs (such as alerts, confirms, or prompts).
      - If your test interacts with dialogs, you can register a dialog handler to accept or dismiss them:
      ```javascript
      page.on('dialog', (dialog) => dialog.accept()); // or dialog.dismiss()
      ```
      e. Verify Page State After Click:
      - After clicking an element, verify that the expected page state (URL, content, etc.) is achieved.
      - Use assertions (e.g., `expect(page).toHaveURL(expectedURL)`) to validate the result.
      3. Example Code:
      - Here's an example of waiting for an element to be clickable:
      ```javascript
      await page.goto('example.com');
      await page.waitForSelector('button'); // Wait for the button to appear
      await page.click('button', { timeout: 5000 }); // Click the button
      ```
      4. Additional Resources:
      - For more details on handling dialogs and other Playwright features, refer to the [official Playwright documentation](playwright.dev/docs/dialogs).
      Remember that debugging flaky behavior often involves trial and error
      --

  • @eddie4249
    @eddie4249 ปีที่แล้ว

    With Playright or in general, do you ever use cookies such as session or CSRF to assert a successful login?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Hi in a test scenario, you might use cookies and tokens to verify that a user has been authenticated and that their session is valid, It will depend on the implementation, most of the times, you may not have to explicitly do this

  • @YogalakshmiKarthi
    @YogalakshmiKarthi 21 วันที่ผ่านมา

    hi Raghav i have learnt playwright by watching ur videos. but am not getting explore option in playwright inspector . can u guide me y am not getting that explore option in playwright inspector

    • @RaghavPal
      @RaghavPal  21 วันที่ผ่านมา

      Yogalakshmi
      If you’re not seeing the Explore option in Playwright Inspector, here’s why and how to fix it:
      Check by Updating Playwright: Run npm install playwright@latest
      Run in Debug Mode: Use npx playwright test --debug
      Disable Headless Mode: Set headless: false in the launch options
      Ensure Navigation: Add await page.goto('example.com') in your test
      Reinstall Playwright (if needed):
      Run npm uninstall playwright
      Then npm install playwright
      Check again for the Explore option..
      -

  • @chandanachinni9717
    @chandanachinni9717 7 หลายเดือนก่อน

    Hi Raghav, My test opens a new tab after login page with dynamic value in the url, and I need to input text into the text fields on the page that opened in new tab. how to handle this?

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน

      Chandana
      When dealing with a new tab that opens dynamically during your test, you can follow these steps to input text into the text fields:
      1. Open the New Tab:
      - Before interacting with the new tab, ensure that you've opened it. You can use Playwright's `context.newPage()` method to create a new page within the same browser context.
      - For example:
      ```javascript
      const newPage = await context.newPage();
      ```
      2. Navigate to the Dynamic URL:
      - If the URL of the new tab is dynamic, extract it from the login process or any other source.
      - Use `newPage.goto(url)` to navigate to the desired URL:
      ```javascript
      await newPage.goto('example.com/dynamic-page');
      ```
      3. Locate and Input Text:
      - Identify the text fields (input elements) on the new tab. You can use various locators such as `page.locator()`, `page.$()`, or `page.$$()` to find the elements.
      - Use the `fill()` method to input text into the fields. For example:
      ```javascript
      await newPage.locator('#username').fill('your-username');
      await newPage.locator('#password').fill('your-password');
      ```
      4. Submit the Form (if applicable):
      - If the text fields are part of a form, submit the form after filling in the required data:
      ```javascript
      await newPage.locator('form').submit();
      ```
      5. Handle Any Other Interactions:
      - Depending on your use case, you might need to perform additional actions (e.g., clicking buttons, selecting options, etc.) on the new tab.
      Remember to adjust the selectors (`#username`, `#password`, etc.) based on the actual HTML structure of the page you're testing
      --

  • @hashcode_01
    @hashcode_01 2 ปีที่แล้ว

    Thanks for creating such nice course
    IMHO writting test for login page should be like bypassing it, wondering if it's a good practice to share the user and pass in the test

    • @RaghavPal
      @RaghavPal  2 ปีที่แล้ว

      Hi Hamid, not very sure, will need to read more on this

    • @peterinvestor
      @peterinvestor 7 หลายเดือนก่อน

      this is more broad question, usually you will use test environment with some fake data so any data leak wont harm BUT from my experience developers are lazy so many times they will use real passwords so what we are doing is to have test users / fake users with fake passwords therefor it is safe however I saw many things in the pass

  • @alejandrosejas
    @alejandrosejas ปีที่แล้ว

    could you do an example using session/cookies instead of actually logging into the app everytime on each test? thanks! great content as always

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      I will check on this Alejandro

  • @ShivMishra-u2q
    @ShivMishra-u2q 6 หลายเดือนก่อน

    Hi Raghav I'm getting the below error everytime I run the test
    Error: No tests found.
    Make sure that arguments are regular expressions matching test files.
    You may need to escape symbols like "$" or "*" and quote the arguments.

    • @RaghavPal
      @RaghavPal  6 หลายเดือนก่อน

      Shiv
      The "No tests found" error in Playwright can occur due to several reasons. Here are some common solutions:
      1. Test File Naming Convention:
      - Ensure that your test files follow the correct naming convention. Playwright expects test files to be suffixed with either `.spec.js` or `.test.js`.
      - If your test file is named differently, rename it to match the expected format (e.g., `first.spec.js` or `second.test.js`).
      Also try adding single forward slash / in your path in the command
      2. Configuration Issues:
      - Check your Playwright configuration. Make sure you've set up your project correctly.
      - Verify that your test runner (e.g., Jest, Mocha) is configured to discover and run tests from the correct files.
      3. File Structure:
      - Confirm that your test files are located in the right directory.
      - Ensure that the path to your test files is accurate when running the tests.
      4. Playwright Extension in VSCode:
      - If you're using the Playwright extension in Visual Studio Code (VSCode), ensure that it's detecting your test files.
      - Sometimes, VSCode may not recognize the tests immediately. Try restarting VSCode or manually triggering the test discovery process.
      Remember to apply these steps based on your specific setup
      -

  • @MamaliTesting
    @MamaliTesting 8 หลายเดือนก่อน

    Can you please give a tutorial where we are solving Image Captcha manually by pausing the execution & later resuming it with login page
    ???

    • @RaghavPal
      @RaghavPal  8 หลายเดือนก่อน

      I will check on this.

  • @nagarajuperftest
    @nagarajuperftest 10 หลายเดือนก่อน

    Hi Raghav garu I have One doubt instead of manually finding locators recoding is better right? Can you confirm which one is better.

    • @RaghavPal
      @RaghavPal  10 หลายเดือนก่อน +1

      Nagaraju
      In Playwright, the choice between manually finding locators and recording your scripts has its pros and cons, and the "better" option depends on your specific situation and preferences. Here's a breakdown:
      Manually Finding Locators:
      Pros:
      - More control: You have full control over which element you're interacting with, ensuring accuracy and specificity.
      - Readability: Well-written locators can be more self-documenting and easier to understand, especially for complex interactions.
      - Maintainability: Locators are less likely to break with minor UI changes compared to recordings.
      - Faster execution: Manually targeting can sometimes be faster than waiting for an entire page to load and record interactions.
      Cons:
      - Time-consuming: Manually finding locators can be time-consuming, especially for complex pages or frequent changes.
      - Requires knowledge: You need to understand HTML structure and various locator strategies (CSS selectors, XPath, etc.).
      - Prone to errors: Incorrect locators can lead to test failures and debugging time.
      Recording Script:
      Pros:
      - Faster initial setup: Recording can be quicker for initial test creation, especially for simple interactions.
      - Less knowledge required: No need to understand specific locator strategies, simplifying initial testing.
      - Captures dynamic content: Can handle dynamic elements that would be difficult to locate manually.
      Cons:
      - Less control: Recordings might capture unnecessary steps or target incorrect elements, requiring adjustments.
      - Maintenance challenges: Recordings can become brittle and break easily with UI changes.
      - Readability issues: Recorded scripts can be long and verbose, making debugging and understanding harder.
      - Performance impact: Recording can add overhead and slow down tests compared to manual targeting.
      Recommendations:
      - Start with recordings: For initial basic tests or exploring functionalities, recording can be a quick way to get started.
      - Refactor to manual targeting: As your tests mature and become critical, refactor recorded scripts to use manual locators for better maintainability and control.
      - Combine approaches: Use recordings for simple interactions and manual targeting for critical actions or elements that might change frequently.
      - Consider tools: Explore tools like Playwright CodeGen or Test Code Generator that can generate more readable and maintainable code from recordings.
      Ultimately, the best approach depends on your specific needs, budget, and team's expertise. Evaluate your priorities and find the balance that works best for your Playwright test automation..

  • @baron_lj
    @baron_lj 4 หลายเดือนก่อน

    I’m trying to do this with PayPal but when I do it windows gives me a passkey option pop up is there a way to suppress this?

    • @RaghavPal
      @RaghavPal  4 หลายเดือนก่อน +1

      Lukas
      Let's break down the problem and potential solutions step by step.
      Problem: When using Playwright for web automation testing on PayPal, a Windows passkey option popup appears, and you want to suppress it.
      Step 1: Understand the passkey option popup
      The passkey option popup is a Windows security feature that allows users to authenticate using a passkey (a password-less authentication method) instead of a traditional password. This feature is enabled by default in Windows 10 and later versions.
      Step 2: Identify the cause of the popup
      The popup is likely triggered by the automated browser session initiated by Playwright, which is trying to access the PayPal website. PayPal's website might be configured to use Windows Hello (a biometric authentication system) or other authentication methods that rely on the passkey feature.
      Step 3: Potential solutions
      To suppress the passkey option popup, you can try the following approaches:
      a. Disable Windows Hello and passkey authentication
      You can disable Windows Hello and passkey authentication on your system. However, this might not be desirable if you need these features for other purposes.
      b. Use a different browser context
      Create a new browser context using Playwright's `browser.newContext()` method, which allows you to create a new browser instance with custom settings. You can try creating a context with `windowsHelloEnabled` set to `false`. Here's an example:
      ```javascript
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext({
      windowsHelloEnabled: false,
      });
      ```
      c. Use a headless browser
      Run Playwright in headless mode, which doesn't display the browser UI and might not trigger the passkey option popup. You can enable headless mode by passing the `headless` option when launching the browser:
      ```javascript
      const browser = await playwright.chromium.launch({ headless: true });
      ```
      d. Use a different authentication method
      If PayPal provides alternative authentication methods, such as username and password, you can try using those instead of relying on Windows Hello or passkey authentication.
      e. Handle the popup programmatically
      As a last resort, you can try handling the popup programmatically using Playwright's automation capabilities. This might involve detecting the popup, clicking on the "Cancel" or "Not now" button, and then continuing with the automation script.
      -

  • @siribn9395
    @siribn9395 ปีที่แล้ว

    Sir, why do we need before each and after each when we can use POM design?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      You're right, using the Page Object Model (POM) design pattern can significantly reduce the need for `beforeEach` and `afterEach` hooks in your test scripts. However, there are still some cases where these hooks can be useful:
      *1. Setup and teardown for global resources:*
      * While POM encloses UI element interactions within page object classes, some tests might require resources not specific to a single page, like setting up a database connection or a test server. `beforeEach` can be used to initialize these resources before each test, and `afterEach` to clean them up after each test.
      *2. Test data management:*
      * POM focuses on UI interactions, but test data preparation and cleanup might be needed outside page objects. `beforeEach` can be used to generate test data, and `afterEach` to clean it up or reset the test environment to its initial state before the next test.
      *3. Browser and WebDriver management:*
      * In some frameworks, like Playwright, you might need to manage the browser instance and WebDriver outside of page objects for efficiency or specific browser configurations. `beforeEach` can be used to launch the browser and WebDriver, and `afterEach` to close them down.
      *4. Context-specific setup and teardown:*
      * Some tests might require specific preconditions or post-conditions that are not relevant to other tests. `beforeEach` and `afterEach` can be used to handle these specific scenarios without cluttering up individual page object methods.
      *5. Reporting and logging:*
      * You can use `beforeEach` and `afterEach` to perform common reporting tasks like capturing screenshots or writing logs at specific points in the test execution.
      *Overall, the need for `beforeEach` and `afterEach` with POM depends on your testing framework and the complexity of your tests.* If your tests require minimal global setup and teardown, POM alone can be sufficient. However, for cases where you need to manage resources, data, or browser instances outside of page object interactions, these hooks can be valuable tools for maintaining clean and efficient test code.
      Remember, the key is to use these hooks judiciously and avoid duplicating setup and teardown logic within page objects and test scripts

    • @siribn9395
      @siribn9395 ปีที่แล้ว

      @@RaghavPal thank you so much for taking your time out to clarify my doubt.

  • @ashitoshsurve248
    @ashitoshsurve248 7 หลายเดือนก่อน

    Can you also share how to automate Log In for resources that require MFA?

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน +1

      I will check on this Ashitosh

  • @mahaboobsabmaniyar7363
    @mahaboobsabmaniyar7363 2 ปีที่แล้ว

    hi sir how to handle multiple dropdowns if in application having 5 dropdown in one page then how to create generic method for that in playwright

    • @RaghavPal
      @RaghavPal  2 ปีที่แล้ว

      this can help stackoverflow.com/questions/66702908/how-to-select-a-dropdown-option-using-playwright-in-javascript

  • @shikhabhargava3132
    @shikhabhargava3132 11 หลายเดือนก่อน

    I don't see explore option in Playwright Inspector it just shows locator and log?

    • @RaghavPal
      @RaghavPal  11 หลายเดือนก่อน

      Shikha
      You're right, the "Explore" option used to be part of Playwright Inspector but it's been removed in more recent versions. It's been replaced by features that offer similar functionality across multiple browsers and are more powerful overall. Here's what you can use instead:
      1. Network: This tab shows all the network requests made by the page during your test run. You can filter by request type, status code, and other criteria, and even inspect the request and response payload in detail. This can be helpful for debugging issues related to API calls, data fetching, or server interactions.
      2. Console: This tab shows all the logs printed to the browser console during your test run. This can be helpful for debugging issues related to JavaScript errors, warnings, or custom logging statements in your test code.
      3. Source: This tab allows you to inspect the source code of the page you're testing. You can navigate through the DOM tree, highlight elements, and view their properties and styles. This can be helpful for understanding the structure of the page and debugging issues related to element identification or interaction.
      4. Elements: This tab shows the DOM tree of the page you're testing. You can expand and collapse nodes, filter by element type or attribute, and inspect individual elements. This can be helpful for identifying the elements your tests are interacting with and debugging issues related to locator selection or element manipulation.
      5. Recorder: While not exactly the same as Explore, the Playwright Recorder offers a similar functionality of recording user actions on a page and replaying them for debugging purposes. This can be especially helpful for identifying intermittent issues that only occur during specific user interactions.
      Remember, Playwright Inspector also provides additional features like stepping through your tests, live editing locators, and viewing actionability logs. These features can be helpful for understanding the execution flow of your tests and debugging issues related to element selection or timing.

    • @shikhabhargava3132
      @shikhabhargava3132 11 หลายเดือนก่อน

      Thanks will try with this @@RaghavPal

  • @sandhyags7713
    @sandhyags7713 2 ปีที่แล้ว +1

    Running 0 tests using 0 workers
    =================
    no tests found.Why this error is coming? Can u pls explain

    • @viralepisodes
      @viralepisodes 2 ปีที่แล้ว +1

      npx playwright test loginPage.spec.ts change the filename only.

    • @RaghavPal
      @RaghavPal  2 ปีที่แล้ว

      thanks for adding

    • @iskender1982
      @iskender1982 2 ปีที่แล้ว

      @@viralepisodes why is it ending as .ts?

    • @iskender1982
      @iskender1982 2 ปีที่แล้ว

      PS C:\Users\idemirka\Documents\Playwrigt_Tutorial_Raghav_youtube> npx playwright test .\tests\example.spec.js
      =================
      no tests found.
      ================= still always like this.

  • @bonnieoyaro
    @bonnieoyaro ปีที่แล้ว

    Hello, do we have away of passing username and password as variable incase they do change in playwright using js

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Yes, we can do that

    • @bonnieoyaro
      @bonnieoyaro ปีที่แล้ว

      How is that done is it possible you share a link somewhere to refer

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      Can declare variables and store values
      let username = "testuser";
      let password = "testpassword";
      and refer these in place of test data

    • @bonnieoyaro
      @bonnieoyaro ปีที่แล้ว

      @@RaghavPal okay will have a look

  • @SonAyoD
    @SonAyoD ปีที่แล้ว

    How can we test our apps locally, all the links you use are deployed apps

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Hi Son,
      Yes you should be able to do that

  • @charetzel
    @charetzel ปีที่แล้ว

    thank you so much sir :)

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Most welcome Charlene

  • @santhoshmayal
    @santhoshmayal 11 หลายเดือนก่อน

    I couldn't find timeout option under the playwright.config file

    • @RaghavPal
      @RaghavPal  11 หลายเดือนก่อน

      Santhosh
      It may be due to version issue, Please check the latest documentation from Playwright

  • @iskender1982
    @iskender1982 2 ปีที่แล้ว

    Hi Raghav , it is wonderful tutorial and thanks a lot but there is a question that i receive always by running throughoutht an error path PS C:\Users\idemirka\Documents\Playwrigt_Tutorial_Raghav_youtube> npx playwright test .\tests\example.spec.js
    =================
    no tests found.
    =================

    • @RaghavPal
      @RaghavPal  2 ปีที่แล้ว

      Hi, You may not have any tests defined in your test code. Make sure that you have written tests and that they are being imported or included correctly in your test runner.
      Also check the test names and location are as per the config file

    • @tester5509
      @tester5509 ปีที่แล้ว

      @asilcan I have similar issue when running with the test file full path. Don't know the reason.
      The workaround: use just some part of the filename. In your case it may look like:
      npx playwright test example

  • @nicholasamodu6676
    @nicholasamodu6676 10 หลายเดือนก่อน

    when i peak locator from explore why is my vscode not accepting it sir e.g getByRole('link', { name: 'Sign in' })

    • @RaghavPal
      @RaghavPal  10 หลายเดือนก่อน

      Nicholas
      The `getByRole('link', { name: 'Sign in' })` method is a powerful way to locate elements based on their explicit or implicit accessibility attributes. However, if VS Code is not accepting it, there might be a few reasons:
      1. Playwright Version Compatibility: Ensure that you're using a compatible version of Playwright with your VS Code extension. Sometimes, discrepancies between versions can cause issues. Make sure both are up-to-date.
      2. VS Code Extensions: Verify that you have the Playwright Test Explorer extension installed in VS Code. This extension enhances your testing experience by providing features like test discovery, debugging, and more.
      3. Code Generator: Playwright has a handy code generator that can help you create locators. It analyzes your page and suggests the best locators based on roles, text content, and test IDs. You can use it to generate a locator and then edit it as needed.
      4. Locator Prioritization: When using locators, prioritize user-facing attributes and explicit contracts. For example, `page.getByRole()` is recommended. If your DOM structure changes dynamically, Playwright will re-locate the element before each action, ensuring resilience.
      Here's an example of how you can use `getByRole('button', { name: 'Sign in' })` to click a "Sign in" button:
      ```javascript
      await page.getByRole('button', { name: 'Sign in' }).click();
      ```
      Remember that the `getByRole()` locator reflects how users and assistive technology perceive the page. It's a robust choice for locating elements based on their roles (e.g., buttons, checkboxes, headings) and follows W3C specifications for ARIA roles and attributes.

  • @shilpareddy2903
    @shilpareddy2903 ปีที่แล้ว

    How to do parameterizations? I dont want to pass username and password in the code

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Shilpa
      To parameterize your Playwright tests, you can use a configuration file or a data provider.
      *Configuration file*
      To use a configuration file, you can create a `config.js` file in the directory where your Playwright tests are located. In the `config.js` file, you can define a `parameters` object that contains the values that you want to use to parameterize your tests.
      For example, the following `config.js` file defines two parameters: `username` and `password`:
      ```javascript
      module.exports = {
      parameters: {
      username: ['alice', 'bob'],
      password: ['secret123', 'password456'],
      },
      };
      ```
      You can then use the `parameters` object in your Playwright tests to access the parameter values. For example, the following test uses the `username` and `password` parameters to log in to a website:
      ```javascript
      test('should log in to the website', async ({ username, password }) => {
      // Navigate to the website.
      await page.goto('example.com');
      // Enter the username and password.
      await page.fill('#username', username);
      await page.fill('#password', password);
      // Click the login button.
      await page.click('#login-button');
      // Wait for the page to navigate to the next page.
      await page.waitForNavigation();
      // Assert that the user is logged in.
      expect(await page.textContent('.username')).toBe(username);
      });
      ```
      *Data provider*
      To use a data provider, you can create a function that returns an array of objects. Each object in the array should contain the values that you want to use to parameterize your test.
      For example, the following function returns an array of objects that contain username and password values:
      ```javascript
      function getUserCredentials() {
      return [
      { username: 'alice', password: 'secret123' },
      { username: 'bob', password: 'password456' },
      ];
      }
      ```
      You can then use the `dataProvider` function to parameterize your Playwright tests. For example, the following test uses the `getUserCredentials()` function to parameterize the test:
      ```javascript
      test('should log in to the website', async ({ username, password }) => {
      // Navigate to the website.
      await page.goto('example.com');
      // Enter the username and password.
      await page.fill('#username', username);
      await page.fill('#password', password);
      // Click the login button.
      await page.click('#login-button');
      // Wait for the page to navigate to the next page.
      await page.waitForNavigation();
      // Assert that the user is logged in.
      expect(await page.textContent('.username')).toBe(username);
      });
      // Pass the `getUserCredentials()` function to the `dataProvider` function.
      dataProvider(getUserCredentials);
      ```
      Which method you choose to parameterize your Playwright tests depends on your personal preference. However, using a data provider is generally considered to be the best practice, as it is more flexible and reusable.
      I hope this helps

  • @sagarikamandal8977
    @sagarikamandal8977 ปีที่แล้ว

    Hi Raghav. Score 5

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Great Sagarika. best wishes

  • @prashantthube
    @prashantthube ปีที่แล้ว

    Hi All , How is the market for Playwright opening currently (second half of 23)

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      Hi Prashant
      The market for Playwright openings is currently very strong. Playwright is a relatively new tool, but it is quickly gaining popularity due to its many advantages. It is a cross-platform tool that can be used to automate web applications on different browsers and platforms. It is also very efficient and can run tests quickly.
      As a result of these advantages, there is a high demand for Playwright engineers. According to a recent survey, the average salary for a Playwright engineer is \$120,000. This is significantly higher than the average salary for a software engineer in general.
      If you are interested in a career in Playwright, now is a great time to start. There are many job openings available, and the demand is only going to grow in the future.
      If you are interested in a career in Playwright, here are some things you can do to prepare:
      * Learn the basics of JavaScript.
      * Learn the Playwright API.
      * Practice automating web applications with Playwright.
      * Attend Playwright meetups and conferences.
      * Network with other Playwright engineers.
      By following these steps, you can increase your chances of landing a job in Playwright.

    • @prashantthube
      @prashantthube ปีที่แล้ว

      @@RaghavPal Thank you for quick and detailed reply , sure I'll follow your suggestions , Thanks Raghav

  • @aceage5910
    @aceage5910 ปีที่แล้ว

    Hi Raghav,
    Can you please tell me how I can generate fake email, username and passwords for my test cases in Playwright ?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      Hi,
      Yes, you can generate fake email, username, and password for your test cases in Playwright using various third-party libraries.
      One such library is faker.js, which is a popular library for generating fake data. Here is an example of how to use it in Playwright:

    • @aceage5910
      @aceage5910 ปีที่แล้ว

      @Raghav I am adding username and password on a login page and clicking on sign in button.
      Page is not changing but on the same page login page elements changed and now I have to fill auth code.
      Means URL is same but elements got changed.
      But playwright is picking previous input field like password and username for the locator I provided their for Auth code.
      What can I do ?

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว

      If the page elements have changed after clicking the sign-in button and now you need to fill in the authentication code, you need to find the new locator for the authentication code field and use it to interact with the field. It's possible that the previous locator you were using is no longer valid since the page elements have changed.
      Here's what you can do:
      Inspect the authentication code field: Right-click on the authentication code field and select "Inspect" or "Inspect Element" to open the browser's developer tools. Look for the HTML code for the authentication code field and note its ID, name, class, or any other relevant attributes.
      Find the new locator for the authentication code field: Use the ID, name, class, or other attributes you found in step 1 to create a new locator for the authentication code field. You can use a different type of locator, such as XPath or CSS selector, if necessary. You can also use the browser's developer tools to test the new locator and make sure it is selecting the correct field.
      Use the new locator to interact with the authentication code field: Once you have the new locator for the authentication code field, use it to fill in the authentication code. For example, if you're using Playwright with Java, you can use the fill() method to enter the authentication code:
      page.fill("#auth-code-field", "1234");
      Replace #auth-code-field with the new locator for the authentication code field, and "1234" with the authentication code you need to enter.
      By following these steps, you should be able to interact with the correct field and enter the authentication code on the login page.

  • @Anto-fz2kw
    @Anto-fz2kw 11 หลายเดือนก่อน

    My score is 4/5. thank

    • @RaghavPal
      @RaghavPal  11 หลายเดือนก่อน

      Great Anto... keep going

  • @peterinvestor
    @peterinvestor 7 หลายเดือนก่อน

    This shows very basic login tests however in real life you will have more complex login logic for example test if message is still the same, if speed is the same, test if 3 incorrect pw will lock user if another 3 will lock him for 3 days, test if user is verified, valid, agreed terms, etc so I guess purpose of these playwright tests is just happy path and no edge case scenarios.

    • @RaghavPal
      @RaghavPal  7 หลายเดือนก่อน +2

      True Peter. This is just to get started for beginners, after this users can try more complex scenarios

  • @sirishapochiraju3551
    @sirishapochiraju3551 ปีที่แล้ว

    Hi Raghav, I have a question every time when we execute the test using npx playwright test command from the Terminal do the playwright inspector utility opens each and every time could we avoid that am not sure . Also, does the Report only show if the test is PASS. Could you give me your contact info if possible can i send questions in whatsapp if its fine or your email id. i'll email all my questions related to the playwright. Thanks

    • @RaghavPal
      @RaghavPal  ปีที่แล้ว +1

      Hi Sirisha
      Yes, by default, when you run npx playwright test command, Playwright will launch the Inspector utility in a new browser window. However, you can disable this behavior by passing the --headed or --headless option to the command.
      For example, to run the test in headless mode and avoid launching the Inspector, you can use the following command:
      npx playwright test --headless
      Regarding the report, it will show the results of all the tests that were executed, whether they passed or failed. If a test fails, the report will show the details of the failure and the reason why the test failed.
      Hope it helps. It will be difficult for me to take personal calls or messages, You can let me know if you have any further questions here

    • @sirishapochiraju3551
      @sirishapochiraju3551 ปีที่แล้ว

      @@RaghavPal Yes Raghav Thanks!