Playwright Beginner Tutorial 5 | How To Record Tests
ฝัง
- เผยแพร่เมื่อ 19 มิ.ย. 2024
- ▬ ALL FREE COURSES ► automationstepbystep.com/
▬ ASK RAGHAV ► bit.ly/2CoJGWf
▬ QUIZ ► forms.gle/C9SbsSc9ZJmnrtZt9
How to record test - Test Generator
Playwright comes with a tool - Codegen also called Test Generator
Can be used to record test and generate test scripts
It Opens 2 windows
A browser window to interacts with the website
Playwright Inspector window to record test
00:00 Intro
01:18 What is Codegen
02:14 Step 1 - Open terminal and run codegen npx playwright codegen
03:04 Step 2 - Check 2 windows open - Browser and Playwright Inspector
04:57 Step 3 - Record your test steps and check the test scripts getting created
06:43 Step 4 - Save the recorded script in a test file | Run and check
10:40 Can also add the url npx playwright codegen google.com
11:48 See all options npx playwright codegen --help
13:33 Screenshot moment
13:54 Record on a specific browser (default:chromium) npx playwright codegen --browser firefox
15:32 Record and save to a file npx playwright codegen --target javascript -o record_example.js
21:27 Set viewport - screen resolution (size) npx playwright codegen --viewport-size=800,600
22:52 Emulate devices npx playwright codegen --device="iPhone 11"
25:15 Emulate color scheme (if available) npx playwright codegen --color-scheme=dark
27:26 Screenshot moment
#playwright #automation #testing
▬▬ CI CD DEVOPS ▬▬
JENKINS BEGINNER ► bit.ly/2MIn8EC
JENKINSFILE ► bit.ly/3JSMSZ7
DOCKER ► bit.ly/2MInnzx
KUBERNETES ► bit.ly/2MJIlMK
▬▬ UI TESTING ▬▬
SELENIUM BEGINNERS ► bit.ly/2MGRS8K
SELENIUM JAVA FRAMEWORK ► bit.ly/2N9xvR6
SELENIUM PYTHON ► bit.ly/2oyMp5x
SELENIUM TIPS ► bit.ly/2owxc50
SELENIUM 4 ► bit.ly/3AiJOlP
KATALON STUDIO ► bit.ly/2wARFdi
ROBOT FRAMEWORK with RIDE ► bit.ly/2Px6Ue9
ROBOT FRAMEWORK with Eclipse► bit.ly/2N8DZxb
TEST PROJECT ► bit.ly/2DRNJYE
CUCUMBER BDD ► bit.ly/3Cnno4z
CYPRESS ► bit.ly/3PpEukM
XPATH & WEB LOCATORS ► bit.ly/3PpEvoQ
▬▬ API TESTING ▬▬
WEB SERVICES (API) ► bit.ly/2MGafL7
SOAPUI ► bit.ly/2MGahmd
POSTMAN ► bit.ly/2wz8LrW
POSTMAN 2022 ► bit.ly/3JWm4qX
JMETER API TESTING ► bit.ly/3AgVPar
GENERAL ► bit.ly/2PYdwmV
KATALON STUDIO API ► bit.ly/2BwuCTN
REST ASSURED ► bit.ly/3zUdhRD
KARATE API ► bit.ly/3w3H5Ku
API MOCKING ► bit.ly/3bYPsjS
▬▬ MOBILE TESTING ▬▬
APPIUM ► bit.ly/2ZHFSGX
MOBILE TESTING ►bit.ly/2PxpeUv
▬▬ PERFORMANCE TESTING ▬▬
JMETER BEGINNER ► bit.ly/2oBbtIU
JMETER INTERMEDIATE ► bit.ly/2oziNVB
JMETER ADVANCED ► bit.ly/2Q22Y6a
JMETER TIPS & TRICKS ► bit.ly/2NOfWD2
PERFORMANCE TESTING ► bit.ly/2wEXbLS
GATLING ► bit.ly/3QrWfkV
▬▬ IDE ▬▬
ECLIPSE ► bit.ly/3AnRhQP
INTELLIJ IDEA ► bit.ly/3AnyDZ8
Visual Studio Code ► bit.ly/2V15yvt
▬▬ PROGRAMMING ▬▬
JAVA BEGINNERS ► bit.ly/2PVUcXs
JAVA TIPS & TRICKS ► bit.ly/2CdcDnJ
JAVASCRIPT ► bit.ly/2KJDZ8o
TYPESCRIPT ► bit.ly/3dvJBmz
PYTHON ► bit.ly/2Z4iRye
RUBY ► bit.ly/3JRRmzf
▬▬ BUILD TOOLS ▬▬
MAVEN ► bit.ly/2NJdDRS
GRADLE ► bit.ly/30l3h1B
▬▬ SOURCE CODE MANAGEMENT ▬▬
GIT & GITHUB ►bit.ly/2Q1pagY
GITLAB ► bit.ly/2kQPGyQ
▬▬ CLOUD SERVICES ▬▬
BROWSERSTACK ► bit.ly/3w7kxZn
SAUCELABS ► bit.ly/3w7kAo1
LAMBDATEST ► bit.ly/3C6TBwM
▬▬ DATA FORMATS ▬▬
JSON ► bit.ly/3w450tq
XML ► bit.ly/3PqRneH
▬▬ MOCK INTERVIEWS ► bit.ly/3QGwwVJ ▬▬
▬▬ RAGHAV PAL ▬▬
GITHUB PROJECTS ► github.com/Raghav-Pal/
STORIES BY RAGHAV ► automationstepbystep.com/stor...
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
Every LIKE & SUBSCRIPTION gives me great motivation to keep working for you
You can support my mission for education by sharing this knowledge and helping as many people as you can
If my work has helped you, consider helping any animal near you, in any way you can
NEVER STOP LEARNING
Raghav Pal
10:40
11:50 all options of *codegen*
22:27 *viewport-size*
thanks for adding timetamps
This is the finest playwright course I've ever come across. Your example is fantastic. Thank you immensely for making many lives easier with your work. Please continue your excellent efforts.
You're very welcome..
Hey Raghav! You are doing a great job! I am learning playwright from your videos only. Kudos!! Great Content!!!
Glad to hear that
Hey Raghav. I'm new to playwright but your video is clear and easy to understand. Thank you for helping a beginner like me.
Glad to hear that Natacha
Thank you so much for the clear and simple explanation with all the details. Your lessons are much better than many courses! You are doing a very useful job and helping a lot of people. God bless you! 🥰
Most welcome Olena.. humbled
Really good, thank you for this videos👌
Glad you like them Carlos
This is so helpful! Thank you so much for your work!
Most welcome Mahpiya
Thank you for great course!
Most welcome
Great job. Thanks a lot.
Most welcome Pallishree
Hi Ragav - when recording I don't have any commented lines explaining the step. Is this a property I need to set? Also, when running a test, sometimes I get "no tests found"...strange because I am using the same folder structure as you and same command.
Hi, you can check your config file and see what is the folder marked for tests
Hi Raghav, your videos are so useful for me, many thanks. One question: which tool do you use in your presentations? (To point, to zoom, etx). Thanks in advance
Hi Nóra
I use mac annotation tools
Hi Raghav! Your videos have always been very helpful for the QA community.. keep doing the amazing work.Thank you for your videos.
I wanted to know if playwright along with any emulator can be used to automate mainframe application? Or is there any other tool in the market which can help automate a mainframe application?
Anushka
not very sure on this, will need to check online
Code gen is an awesome, Thanks for teaching us, lots of respect From Pakistan.
Most welcome
Hi Rahav, thank you for this video, the command also worked with single quotes, 'iPhone 11' , sharing for information, thanks again.
Great.. all the best
thanks for another great video
Thanks for watching!
Hi raghav, this is amazing content for of all, really apprciate this. I just have a small question, what keyboard short cut are you using to call a file into your command for example when using npx playwright test ------- how are you able to get a file name in this blank section without typing manually?
Anurag
you write the 1st few letters and then press tab on keyboard
Hi Raghav! your tutorials make our lives very easy indeed! I have a question, can we create a dashboard using Playwright , like the way we create for cypress? Also can you plz provide some guidance about adding Playwright into Circle CI?
Asma
Yes, you can create a dashboard using Playwright, like the way you create for Cypress. There are a few different ways to do this, but one popular approach is to use the Playwright Test Runner and the Playwright-Report library.
The Playwright Test Runner is a command-line tool that can be used to run Playwright tests. It also has the ability to generate JSON reports that contain information about the test results. The Playwright-Report library can be used to generate HTML reports from these JSON reports.
To create a dashboard using Playwright, you will need to do the following:
1. **Run your Playwright tests using the Playwright Test Runner and generate JSON reports.**
2. **Use the Playwright-Report library to generate HTML reports from the JSON reports.**
3. **Host the HTML reports on a web server.**
4. **Create a dashboard that displays the HTML reports.**
Here is an example of how to create a dashboard using Playwright and the Playwright-Report library:
```javascript
const playwright = require('playwright');
const playwrightReport = require('playwright-report');
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// Run your Playwright tests
await page.goto('www.example.com');
await page.click('button');
// Generate JSON report
const report = await playwrightReport.createReport();
report.json('report.json');
// Generate HTML report
report.html('report.html');
await browser.close();
})();
```
This code will run a simple Playwright test and then generate a JSON report and an HTML report. You can then host the HTML report on a web server and create a dashboard that displays the report.
To add Playwright into Circle CI, you will need to do the following:
1. **Add the Playwright NPM package to your project's dependencies.**
2. **Create a Circle CI configuration file that specifies the steps for running your Playwright tests.**
Here is an example of a Circle CI configuration file for Playwright:
```yaml
version: 2.1
jobs:
build:
docker:
- image: circleci/python:3.8
steps:
- checkout
- setup_python
- install:
method: pip
packages:
- playwright
- run:
name: Run Playwright tests
command: playwright test
```
This configuration file will checkout your project's code, install the Playwright NPM package, and then run your Playwright tests.
I hope this helps
hey Raghav. Amazing videos so far. Very easy to follow and straight forward. Thank you for making them. Just one issue im having though, for some reason when i use my code generator it doesnt comment the steps like yours does in the video. Any ideas on how to fix this? its a really cool feature that i would like for my tests to include
Hi Oscar
In order to generate comments in Playwright code using a code generator, you will need to ensure that the code generator is specifically designed to generate comments for each step in your test code.
One way to do this is to use a code generator that has built-in support for generating comments. For example, you can use the Playwright Test Codegen tool, which automatically generates code with comments that explain each step.
If you are using a custom code generator or have modified an existing one, you may need to update the generator's code to include comments. To do this, you will need to modify the code generation logic to generate comments along with the test code.
Here's an example of how to add a comment to a Playwright step:
// Navigate to the login page
await page.goto('example.com/login');
// Enter the username and password
await page.fill('#username', 'myusername');
await page.fill('#password', 'mypassword');
// Click the login button
await Promise.all([
page.waitForNavigation(),
page.click('#login-button')
]);
// Verify that the user is logged in
const element = await page.$('#welcome-message');
const text = await element.textContent();
expect(text).toContain('Welcome,');
In this example, each step is commented with a description of what it does. You can modify the comments to suit your needs.
Remember to always keep your comments up to date as you modify your test code, to ensure that they accurately reflect the behavior of your tests.
@@RaghavPal I am using the codegen from playwright exactly like you showed in the video by typing command "npx playwright codegen" but it doesnt automatically generate the comment in the steps. is there somewhere i need to go to turn on this feature or is it supposed to automatically do it?
Hi Oscar, not sure if there are any updates in the new version. Will need to check online
@@RaghavPal i am having the same issue, no comment generated automatically and I am using the latest playwright
Thank you. Quiz score 9/10
Great going Kelly...
Thank you for the material , very useful. What is the recommend viewport-size? I tried different ones and cannot solve my issue. When I am recording, the web page scroll bar is gone and I cann scroll down to continue and see the web content.
The recommended viewport size for Playwright is 1280x720. This is the default viewport size for most desktop browsers.
If you are having problems scrolling down on a web page when recording with Playwright, it is possible that the viewport size is too small. To fix this, you can try increasing the viewport size.
To do this, you can use the `browser.newContext()` method to create a new browser context with a larger viewport size. For example, the following code will create a new browser context with a viewport size of 1920x1080:
```javascript
const browser = await playwright.chromium.launch();
const context = await browser.newContext({ viewport: { width: 1920, height: 1080 } });
```
Once you have created a browser context with a larger viewport size, you can use it to record your test.
Here is an example of how to record a test using a browser context with a larger viewport size:
```javascript
const page = await context.newPage();
await page.goto('example.com');
// Record the test.
await context.startRecording({ path: 'test.mp4' });
// ...
// Stop the recording.
await context.stopRecording();
```
This will record a video of the test with a viewport size of 1920x1080.
If you are still having problems scrolling down on the web page, you can try increasing the viewport size even further. You may also want to try using a different browser or browser version.
Another possible reason why you are having problems scrolling down on the web page is that the web page is not designed to be scrolled on a small screen. If this is the case, you may need to contact the developer of the web page and ask them to fix the problem.
hi Raghav, how to handle dynamically changing web table. I have a task list table where tasks are generated auotmatically based on user action. there is common link to get to each tasks details and only unique element is Document ID. there can be same task name for different documents and i want to click on view for a particular document. Any advice will be appreciated.
Hi, pls check if this helps - www.way2automation.com/handle-dynamic-webtable-using-scope-locator-in-playwright-java/
stackoverflow.com/questions/65689719/is-there-a-way-in-playwright-to-select-a-specific-button-inside-a-dynamic-table
Hey Raghav quick question if I were to run my test script on iPhone device. What would be command for it. Will it be something like npx playwright test demo.spec.js codegen --device="iPhone 12"? I have already ran this and got an error.
Abdullah
While you can't directly run Playwright tests on real iPhone devices, you can effectively emulate them using Playwright's built-in emulation capabilities. Here's the correct command and steps:
1. Install Playwright:
```bash
npm install -D @playwright/test
```
2. Write your test script (demo.spec.js):
```javascript
// Example test script
test('Emulate iPhone 12 and test', async ({ page }) => {
await page.emulate(iPhone 12);
// Your test actions here
});
```
3. Run the test with emulation:
```bash
npx playwright test demo.spec.js --device="iPhone 12"
```
Key points:
- Emulation: Playwright simulates browser behavior on the specified device, including viewport, user agent, and touch events.
- Device name: Ensure you use the correct device name as defined in Playwright's list (e.g., "iPhone 12", "iPad Pro", "Pixel 2").
- Codegen flag: The `--codegen` flag is used for code generation, not device emulation.
Troubleshooting the error:
- Check device name: Double-check that you've used the correct device name as recognized by Playwright.
- Update Playwright: Ensure you have the latest version of Playwright installed for the latest device support.
- Review available devices: List available devices using `npx playwright devices`.
- Inspect error message: Share the specific error message for more tailored guidance.
Additional considerations:
- Limitations of emulation: Emulation might not capture all nuances of real device behavior. Consider real device testing for comprehensive coverage.
- Cloud-based testing: Services like BrowserStack or SauceLabs offer real device testing with Playwright.
I hope this helps!
Hey Raghav, am not seeing the comments you mentioned @08.54, is there a way to enable/disable them? Also pleas cover how reports are generated, am not seeing the reports getting autogenerated as in your case.
Ayush
Can try this command
npx playwright codegen --comments
Hi, Codegen is opening browser in incognito window but some websites are restricting the access in incognito mode.
Can you please suggest?
Playwright Codegen by default opens the browser in incognito mode. However, if you want to use it without incognito mode, you can use a custom setup. In this case, you would be able to provide `executablePath` to your own `browserType.launch` call
Here is an example of how you can launch a non-incognito browser session with Playwright:
```python
from playwright.sync_api import sync_playwright
import os
user_dir = '/tmp/playwright'
if not os.path.exists(user_dir):
os.makedirs(user_dir)
with sync_playwright() as p:
browser = p.chromium.launch_persistent_context(user_dir, headless=False)
```
In this example, a new browser context is launched using the `launch_persistent_context` method, which does not use incognito mode⁴.
Please replace `'/tmp/playwright'` with the path where you want to store your user data. This will launch the browser with a persistent context using the user data directory specified, allowing you to maintain cookies, cache, and other browsing data across different browser sessions⁴.
Remember to replace `'chromium'` with the browser type you are using (it could be `'firefox'` or `'webkit'`).
Hi Raghav, quick question - when I try to record - I dont see the javascript or plywright test in the target to copy the code? I was using for a while but I couldnt find it anymore. Do you have an suggestion?
Hi Nividya, do you get Playwright Inspector, Pls check the steps again
@@RaghavPal Hi Raghav, I too have the same problem. PW Inspector comes up but I don't see Playwright Test. I see Test Runner and Library under NODE.JS.
Hej! I'm trying to do the same test but i did not get (Expected ) when i klicked on Loggin button. How kan i get it in my recording test ?
Suzan
To capture the expected behavior when clicking the login button in your Playwright test, you need to explicitly define the expected result using assertions. Assertions verify that the application's behavior matches your expectations.
In this case, you can use the `toHaveText` assertion to check if the element's text content matches the expected "Log In" text:
```javascript
await page.locator('button[type="submit"]').click();
await page.waitForSelector('body'); // Wait for page content to load
const loginButtonText = await page.locator('button[type="submit"]').textContent();
await expect(loginButtonText).toHaveText('Log In');
```
This code first clicks the login button, waits for the page content to load, and then retrieves the button's text content using the `textContent` method. Finally, it uses the `expect` function and the `toHaveText` assertion to verify that the text content is indeed "Log In".
If the assertion fails, Playwright will throw an error, indicating that the actual behavior does not match the expected behavior. This helps you identify and debug issues in your test.
Hi Raghav! How can i have Playwright test as target in the Playwright Inspector? At the moment my target is Test Runner, one of the two options under Node.js
Let's explore how to set Playwright Inspector to target your Playwright tests directly:
1. Playwright Inspector Overview:
- The Playwright Inspector is a powerful GUI tool designed to help you debug and troubleshoot your Playwright tests.
- It allows you to step through your tests, live edit locators, pick locators, and view actionability logs.
2. Opening the Playwright Inspector:
- To open the Playwright Inspector, you need to run your tests with the `--debug` flag.
- When you run your tests in debug mode, Playwright configures itself for debugging and automatically opens the inspector.
3. Steps to Run Tests with Playwright Inspector:
- Add the `--debug` flag to your command line when running your Playwright tests. For example:
```
npx playwright test --debug
```
- This command launches the Playwright Inspector alongside the browser that opens in headed mode (i.e., with a visible browser window).
4. What to Expect in the Playwright Inspector:
- Once the inspector opens, you'll have access to the following features:
- Live Debugging: Click on locators in the inspector to highlight corresponding elements in the browser window.
- Locator Editing: Edit locators directly in the inspector, and see the changes reflected live in the browser.
- Actionability Logs: View logs related to actions performed during test execution.
- Breakpoints: Set breakpoints in your test code to pause execution and inspect variables.
- Browser Selection: You can choose different browsers for debugging (e.g., Chromium, Firefox, or WebKit).
5. Additional Notes:
- By default, debugging is done using the Chromium profile. However, you can select a different profile (e.g., Firefox) for debugging.
- Right-click on the debug icon in the testing sidebar to choose the desired profile.
- Each time you run your test in debug mode, it will use the selected profile.
Remember that the Playwright Inspector provides a rich debugging experience, allowing you to interactively troubleshoot your tests.
Hi Raghav! Great explanation. I have one question, when we can generate the code using codegen.. Why do we need to write the code manually? We can just record it and execute everytime right? 🤔 Btw I'm new to the JS and all the other languages.
Hi Naresh
In general we use the recording option to quickly help us with locators and scripts and then edit, add, modify as per our needs
Also once we learn and know how to write, add, edit code manually, it will be easy to understand and work with auto-generated code
It will also give us flexibility and will be easy to debug when needed
I hope this helps
@@RaghavPal Yes! Thankyou 😃
Hi Ragav,
In my Playwright Inspector it does not add commented out explanations for each step. Also it doesn't perform assertion using expect.
Secondly, the Target options are different.
Does it require a setting from somewhere? I followed every single step together with the video.
The version I use is 1.30.0 May that be the reason?
Thanks in advance
Hi Akif,
It's possible that the version you are using (1.30.0) could be the reason for the differences you're encountering in the Playwright Inspector. However, without more information, it's difficult to say for sure. I suggest checking the official documentation or reaching out to the community for support to see if they can help resolve your issue.
@@RaghavPal Hi Raghav. First of all, thank you so much for answering in such a short time. Yes, I figured out that the reason was the version. When I updated the version as 1.25.1 which is the one you installed in the tutorials it started generating the test step descriptions and the assertions same as the tutorials 👍
Hi Ragav, Thanks for the amazing tutorials. Can you tell me how to do this when we have a OTP flow which comes to the email?
Hi Purnima
Here are the steps on how to handle an OTP flow in Playwright:
1. Retrieve the OTP from the email. You can use the Playwright API to retrieve the OTP from the email. The Playwright API provides a Page.waitForSelector() method that you can use to wait for the OTP to be displayed in the email. Once the OTP is displayed, you can use the Page.evaluate() method to retrieve the OTP
2. Enter the OTP into the OTP field. Once you have retrieved the OTP, you can enter it into the OTP field on the website. You can use the Playwright API to find the OTP field and then use the Page.type() method to enter the OTP
3. Submit the form. Once you have entered the OTP, you can submit the form by clicking on the submit button. You can use the Playwright API to find the submit button and then use the Page.click() method to click on it
Here is an example of how to handle an OTP flow in Playwright:
import playwright
def handle_otp_flow(page):
# Retrieve the OTP from the email.
otp = page.evaluate('document.querySelector("#otp").textContent')
# Enter the OTP into the OTP field.
page.type("#otp", otp)
# Submit the form.
page.click("#submit")
if __name__ == "__main__":
context = playwright.chromium.launch()
page = context.new_page()
page.goto("example.com/")
handle_otp_flow(page)
context.close()
This code will first retrieve the OTP from the email. Then, it will enter the OTP into the OTP field on the website. Finally, it will submit the form
I hope this helps
@@RaghavPal Thank you so much for the clear response. This is indeed helpful.
Hello Raghav, Can I use emulator to run the test cases. Can you share the command needed? TIA
Hi Soumya,
Yes, you can use Playwright to run tests in an emulator. Here is an example command to launch an Android emulator and run Playwright tests in it:
playwright-cli install
playwright-cli launch-android --emulator="Pixel_3a_API_30" --no-sandbox
playwright-cli test
In this command, playwright-cli install installs the necessary dependencies, playwright-cli launch-android launches an Android emulator (in this case, the "Pixel_3a_API_30" emulator), and playwright-cli test runs the Playwright tests in the emulator.
You can replace "Pixel_3a_API_30" with the name of the emulator you want to use. You can also specify additional options for launching the emulator, such as the screen size and orientation.
Keep in mind that running tests in an emulator can be slower than running them on a physical device, so you may want to consider using a physical device for faster test execution.
I am using Playwright to write a test until we find out paid tool. I noticed on your video when it was recorded it added assertion. Does it add automatically? I have Playwright version 9.5.0 but I do not see an assertion added to it.
The assertion you observed in the video might have been added manually by the person creating the test. Playwright itself does not automatically add assertions to the tests.
Assertions are an important part of testing and are typically added by the test author to verify the expected behavior of the application under test. Playwright provides various methods and APIs to interact with elements on the page, perform actions, and retrieve information. However, it does not automatically generate assertions based on the actions performed.
To add assertions in your Playwright tests, you can use any assertion library or framework of your choice, such as Chai, Jest, or Node.js assert. These libraries provide a set of assertion methods that you can use to validate the expected results of your tests.
Here's an example of using Chai assertion library in a Playwright test:
const { chromium } = require('playwright');
const { expect } = require('chai');
(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('example.com');
// Perform actions on the page
// Example assertion using Chai
const pageTitle = await page.title();
expect(pageTitle).to.equal('Example Domain');
await browser.close();
})();
In the above example, the expect assertion method from the Chai library is used to assert that the page title is equal to 'Example Domain'. You can add similar assertions based on the expected behavior of your application.
Remember to install the assertion library of your choice (chai, jest, etc.) using npm before using it in your Playwright tests.
Keep in mind that adding assertions is an important aspect of test design to ensure the reliability and accuracy of your tests.
Hello Ragav,
For me the below command is not saving the recorded script to a file:
npx playwright codegen --target javascript -o record_example.js
But the below saves:
npx playwright codegen --target javascript -o .\tests
ecord_example.js
I mean the path from the root.
You are doing great!
Thanks,
Balaji
Hi Balaji, pls check the path is correct, try pressing tab to autocomplete the path
@@RaghavPal I will check once again and let you know. Thanks!
I have tried and working fine.
npx playwright codegen --target javascript -o ./tests/e2e/record2_output.spec.js
Hi raghav whenever a run a command to start the test it shows " 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." i am following the same method as you can you please help i am using typescript
also when i create a new test file in "tests" file is comes in blue in color not in orange as before tests
Bhavesh
Let's address both of your concerns:
1. No Tests Found Error:
When you encounter the "No tests found" error in Playwright, it usually means that the test runner couldn't find any test files to execute. Here are a couple of things you can check:
- Test File Naming Convention:
Ensure that your test files follow the correct naming convention. By default, Playwright Test looks for files with either `.spec.js` or `.test.js` suffixes. If your test file has a different name, it won't be picked up automatically. You can either rename your test file to end with `.spec.js` or `.test.js`, or configure Playwright Test to recognize a different pattern.
- Test Match Configuration:
If you want to use a custom naming pattern for your test files, update your `playwright.config.ts` file. Add the `testMatch` property to specify glob patterns or regular expressions that match your test files. For example:
```typescript
// playwright.config.ts
module.exports = {
// Other configuration options...
testMatch: ['/my-custom-pattern/*.js'], // Adjust the pattern as needed
};
```
- Example File Working:
You mentioned that the example file works. Make sure that your custom test file structure and naming align with the example file that's working.
2. Test File Color in VS Code:
The color of your test files in VS Code is determined by the file extension and the associated language. By default, `.js` files are colored differently from `.ts` files. If your test files are appearing in blue (which is typical for TypeScript files), it's because they are recognized as TypeScript files.
- File Extension:
If you want your test files to appear in orange (like JavaScript files), you can either:
- Rename your test files to have a `.js` extension (e.g., `first.spec.js`).
- Keep them as TypeScript files (`.ts`) and accept the blue color, which is more appropriate for TypeScript code.
Remember to adjust your configuration and file naming as needed, and your tests should run smoothly
@RaghavPal
Hi Raghav,
Thanks for creating easy videos and sharing knowledge.
I would like to bring to your attention when we follow the same folder and file structure as you show in the video. Upon executing the below command through the terminal
npx playwright test .\tests
ecord1.spec.js --project=chromium --headed
we get Error: No tests found
To successfully execute the tests we should enter the command as below in the Terminal
npx playwright test .\\tests\
ecord1.spec.js --project=chromium --headed
Hope this helps the next one who encounters the same error.
Cheers, JB
Try using single forward slash in the path of the test file
@@RaghavPal Thanks for the quick response. Single forward slash in the path of the test file also works. Cheers JB
Raghav, another question: why did you save the file as ".spec.js" and not as simply ".js"?
In Playwright, the choice of saving files with the `.spec.js` extension is a common convention used in testing frameworks. Let me explain why:
1. Test File Naming Convention:
- The `.spec.js` extension is often associated with test files. It indicates that the file contains test cases or specifications.
- By following this convention, developers can easily identify which files are related to testing within a project.
2. Clarity and Organization:
- Separating test files from other JavaScript files (such as utility functions or application code) helps maintain a clear project structure.
- When you see a `.spec.js` file, you immediately know it's related to testing, making it easier to locate and manage test cases.
3. Integration with Testing Tools:
- Many testing tools and libraries (such as Jest, Mocha, and Cypress) automatically discover and execute files with the `.spec.js` extension.
- These tools recognize test files based on naming conventions, allowing seamless integration with test runners.
4. Avoiding Confusion:
- Using `.spec.js` helps prevent confusion between test files and other JavaScript files.
- Without this convention, you might have multiple `.js` files (including both test files and application code), leading to potential mix-ups.
In summary, while you can technically save test files with any extension, adopting the `.spec.js` convention enhances clarity, organization, and compatibility with testing tools. It's a best practice widely followed in the testing community
you can also use auto-complete for other commands like playwright, not just dir paths
thanks for adding Emanuil
Hi Raghav!
I tried the same steps as mentioned in the video. When I run the script using command : npx playwright test .\tests\login.spec.js it throws an error : "Error: No tests found"
Hi Prajakta
The error message "Error: No tests found" means that the Playwright test runner did not find any tests to run. This can happen for a few reasons, including:
* The .\tests\login.spec.js file is not a valid Playwright test file.
* The .\tests\login.spec.js file is not in the current directory.
* The .\tests\login.spec.js file is not named *.spec.js.
To resolve this issue, you can try the following:
* Make sure that the .\tests\login.spec.js file is a valid Playwright test file.
* Make sure that the .\tests\login.spec.js file is in the current directory.
* Rename the .\tests\login.spec.js file to *.spec.js.
If you have checked all of these things and you are still getting the error, you can try posting a question on the Playwright forum or mailing list. There are a number of experienced Playwright users who can help you troubleshoot the issue.
Here are some additional things to keep in mind:
* Playwright test files must be named *.spec.js.
* Playwright test files must be in the current directory or in a sub-directory of the current directory.
* Playwright test files must contain valid Playwright test code.
*
I hope this helps
I have NPX version 9.5.0 and Node version 18.15 but I do not see a comment in Playwright Inspector. Also, I see you have Target: Playwright test and I have Target: Test Runner in the Inspector. Is that due to a different version or configuration?
The differences you're seeing in the Playwright Inspector may be due to a different version or configuration.
The comment feature was introduced in Playwright version 1.17.0, so if you have an older version of Playwright, you may not see the comment feature in the Inspector.
Regarding the "Target" in the Inspector, it depends on how you're running your tests. If you're using the Playwright Test API, the Inspector should show "Target: Playwright Test" as the target. If you're using the Playwright API directly or running your tests through a test runner like Jest or Mocha, the Inspector may show "Target: Test Runner" instead.
It's also possible that the differences you're seeing are due to a configuration issue. I would recommend double-checking your Playwright and Node.js versions to ensure that they're up-to-date, and verifying that you're using the correct syntax for the comment feature if you're trying to use it.
If you're still having issues, you can try reaching out to the Playwright community or filing an issue on the Playwright GitHub repository for further assistance.
I am working as tester on salesforce application but mostly do manual testing , don't get a chance to automate, so as a part of 5 working days I am not getting chance to hands on experience on automation testing so what should I do sir?
Hi MD, take out 1,2 hrs daily and more time on weekend, create a plan with what topics, tools you will learn and show me
raghav- Is npx -v the command to check playwright inspector version. I am not getting comments when using record option to generate scripts
The command `npx -v` is used to check the version of a globally installed package, not the Playwright Inspector version. To check the Playwright Inspector version, you can use the following command:
```
npx playwright --version
```
This will output the version of Playwright, which includes the Inspector.
I understand you're not getting comments when using the record option to generate scripts. Here are some things to check:
1. Enable Comments:
- By default, Playwright doesn't include comments in the generated scripts. You need to enable the `codeGenerationComments` option:
```
npx playwright record --codeGenerationComments > script.js
```
2. Check Selector Types:
- Playwright generates comments only for specific selector types, like text content, CSS selectors, and XPath. For less specific selectors like `page.locator('[data-test-id="button"]')`, comments might not be generated.
3. Consider Third-Party Tools:
- If you need more comprehensive comments, consider using third-party tools like Playwright CodeGen or Playwright Test Code Generator. These tools offer more customization options for comments and code generation.
4. Inspect Generated Code:
- Open the generated script file and search for the keyword "/*". If you find them, it means comments are being generated but might not be in the format you expect.
5. Playwright Version:
- Ensure you're using a recent version of Playwright. Recent versions might have more robust comment generation functionalities.
Hello Raghav Sir, sometime when we stop recording , code is not getting fetch on VS , I am stopping the recording and than close the browser npx playwright codegen --target javascript -o .\tests\cs_demo2.spec.js , its recoding every step one code is not coming on vs, any suggestion
Chandan
When working with Playwright in VS Code, there are a few steps you can take to ensure that your recorded code is correctly fetched and displayed. Let's troubleshoot the issue:
1. Check Your Configuration:
- First, verify that your `playwright.config.ts` file is correctly configured. Specifically, ensure that the `testDir` property points to the folder containing all your tests.
- Example configuration in `playwright.config.ts`:
```typescript
export default {
// Other configurations...
testDir: './e2e', // Make sure this points to your test folder
};
```
- Adjust the `testDir` path according to your project structure².
2. Recording and Code Generation:
- When you stop recording, Playwright should generate the test code directly in VS Code. However, if you encounter issues, try the following:
- After stopping recording, manually save your test file (`cs_demo2.spec.js`) in VS Code.
- Run the code generation command again:
```
npx playwright codegen --target javascript -o .\tests\cs_demo2.spec.js
```
- Check if the generated code now appears in your test file.
3. Debugging and Troubleshooting:
- If the code still doesn't appear, consider the following steps:
- Open the VS Code command palette (Ctrl+Shift+P) and run the command "Playwright: Show Test Report."
- Look for any error messages or warnings related to test discovery or code generation.
- If there are errors, address them based on the information provided in the report.
- Ensure that your test file (`cs_demo2.spec.js`) is saved and not open in any other editor or application.
4. Run Tests and Show Browsers:
- To visualize your tests, you can run them and show the browsers. In the testing sidebar, select "Show Browsers."
- Click the green triangle to run your test, and the browser will open, allowing you to visually observe the test execution¹.
5. Debugging Tests:
- If you encounter further issues, consider debugging your tests directly in VS Code:
- Use breakpoints to pause execution at specific lines.
- Inspect variables and step through your test code.
- Check for any errors or unexpected behavior.
Remember that Playwright's integration with VS Code provides powerful debugging capabilities, so take advantage of them to identify and resolve any issues.
..
Easy to understand. Score 9/10 in quiz.
Great Sagarika
Hi Raghav, Thank you for the video. I chose typrescript when setting this up. While following this video, when you were explaining about this command "npx playwright codegen --target javascript -o .
ecord2_demo.spec.ts", I used typescript instead of javascript but it didn't start the browser and recorder. Please could you clarify the reason. Also, it didn't save the script in the new file, like it didn't to you in VScode editor, many thanks.
You're right, the `playwright codegen` command doesn't support generating TypeScript files at this time. There are a few things you can do to address this:
1. Generate JavaScript Code and Manually Convert to TypeScript:
- Run the command with the correct extension: `px playwright codegen --target javascript -o .
ecord2_demo.js`
- This will create a JavaScript file with the recorded interactions.
- Open the generated JavaScript file in your preferred IDE or editor.
- Manually convert the code to TypeScript using a linter or transpiler like tsc or Babel. Remember to install the necessary TypeScript types for Playwright.
2. Record Manually:
- Use Playwright's built-in recording functionality within your browser developer tools.
- Open your website in a Chromium-based browser (Chrome, Edge).
- Go to the Developer Tools (F12 or Ctrl+Shift+I).
- Open the Playwright tab.
- Click the "Start Recording" button and interact with your web page.
- Click "Stop Recording" when finished.
- Playwright will generate JavaScript code for your recorded interactions.
- As before, you can manually convert this code to TypeScript.
3. Explore Alternative Code Generation Tools:
- While Playwright's own code generation doesn't support TypeScript, some community-developed tools might offer this functionality.
- Do some research to see if any options fit your needs, but be cautious about unofficial tools and check their compatibility and security before using them.
Additional Tips:
- For clarity, consider renaming the output file extension to `.spec.js` (JavaScript) or `.spec.ts` (TypeScript) depending on the approach you choose.
- Ensure you have installed the necessary dependencies for Playwright and TypeScript in your project.
I hope this helps..
thanks a lot for all the suggestions, will follow the instructions.@@RaghavPal
Hi Raghav, thanks for the amazing learning video but i have some queries, how can i connect with you
Right here Saloni
You can let me know your questions
Thank you so much. could you please make it azureDevops ci cd integration?
I will plan Shahzil
Hi Raghav when I run the test files I am getting an error like no tests found in the terminal
Hi Likitha
If you are getting an error like "no tests found" in Playwright, it usually means that your test files are not being detected by the test runner. Here are a few things you can check:
Make sure your test files are located in the correct directory: By default, Playwright looks for test files in a directory called "tests". Make sure your test files are located in this directory, or update the Playwright configuration to point to a different directory.
Check your test file naming convention: By default, Playwright looks for files with the extension ".spec.ts". Make sure your test files are named using this convention.
Make sure your test files contain at least one test: Playwright will only run test files that contain at least one test. Make sure your test files contain at least one test function, such as one defined using the Jest "test" function.
Check your test runner configuration: Make sure your test runner configuration is correctly set up to detect and run Playwright tests. For example, if you are using Jest as your test runner, make sure you have installed the "jest-playwright" package and configured it in your Jest configuration file.
If none of these steps help resolve the issue, you may need to provide more information about your specific setup and configuration.
Hi Raghav,
Will this beginner playwright tutorial help me to get a entry level / junior qa job?
Yes it will.. make sure you do hands-on and create your project.
You can also upload your project on github and add url in your resume
I followed this tutorial and have a question - when we have only chromium browser defined in const then how come the scripts ran into firefox etc
By default, Playwright launches the browser executable defined in the `executablePath` argument within the browser type's configuration. If not specified, it tries to find the system-wide installation. However, Playwright also supports cross-browser testing by accepting an array of browser type configuration objects:
```javascript
const { chromium, firefox, webkit } = require('playwright');
(async () => {
const browsers = [chrome, firefox, webkit]; // Array of browser configurations
for (const browserType of browsers) {
// Launch each browser individually
const browser = await browserType.launch();
// ... execute your test steps using the browser ...
await browser.close();
}
})();
```
In this example, Playwright will sequentially launch Chromium, Firefox, and WebKit according to your system-wide installations.
Key Considerations:
- System-Wide Installations: When you omit the `executablePath`, Playwright searches for the relevant browser executables in common locations on your system (e.g., `/usr/bin/chromium-browser` for Chromium). Ensure these browsers are installed and accessible.
- Command-Line Flags: You can provide command-line flags like `--browser=` to explicitly control the target browser.
- Environment Variables: Browser-specific environment variables like `CHROMIUM_PATH`, `FIREFOX_PATH`, etc. can influence browser selection if `executablePath` is not used.
- Browser Availability: If a browser type is not available on your system or cannot be found, Playwright may skip it or throw an error.
Resolving Execution with Only Chromium Defined:
- Multiple Browser Versions: If you have multiple Firefox versions, Playwright might choose the first one it finds. Use `executablePath` to specify the desired version.
- Environment Variables: Check if environment variables are overriding your intended behavior. Set them appropriately.
- Debugging: Run Playwright with the `--verbose` flag for detailed logging to help identify the actual browser execution.
Hi Raghav. While i follow this procedure as shown in video, the test is not running and showing error in terminal.
Chitresh
I will need more details on this
Recently addicted to your videos and got 8 out of 10 in quiz
Great score Gayathri
Hi Raghav, how do we access element in using codegen. The inspector window does not record any steps or actions taken on elements present in
Hi Deeksha,
In Playwright, you can access elements in an by switching the context to the , and then finding the desired element within the .
Here is an example in JavaScript:
const frame = await page.frames().find(f => f.name() === 'Name');
const element = await frame.$('#elementId');
In this example, page.frames() returns a list of all frames in the current page, and find() is used to select the desired based on its name or ID. $() is then used to locate the desired element within the .
If the does not have a name or ID, you can access it using its index:
const frame = page.frames()[index];
const element = await frame.$('#elementId');
Once you have located the desired element within the , you can interact with it just like you would with any other element in Playwright
@@RaghavPal Thanks a lot Raghav for your response. I need to understand how can we achieve this using Test Generator (Codegen) . Would it be possible to switch the context to in codegen window? Any help would be deeply appreciated. Any demo video or link to relevant documentation.
I will need to try on it, For now check if you find any online examples
When I use the command npx playwright codegen --target javascript -o new.spec.js , the recorded script is not shown in my test case new.spec.js
Hi Aggie,
When you use the npx playwright codegen command to generate a test script, the script will be printed to the console output by default, not saved to a file. To save the generated script to a file, you need to use the > symbol to redirect the console output to a file. Here is an example command that will save the generated script to a file called new.spec.js:
npx playwright codegen --target javascript > new.spec.js
This command will generate the test script and redirect the console output to the file new.spec.js. If the file already exists, it will be overwritten with the new contents of the generated script.
Once you have saved the generated script to a file, you can open the file in your text editor or IDE to see the contents of the script. If the generated script is not showing up in your test case file, make sure that you have saved the script to the correct file and that the file is located in the correct directory relative to your test case file.
Hi Raghav....can we integrate playwright with browserstack?
If yes could you please provide the link if you have already covered this scope ?
Ashwini
Yes, Playwright can be integrated with BrowserStack. This allows you to run your Playwright tests on BrowserStack's cloud platform, which gives you access to a wide range of browsers and operating systems.
To integrate Playwright with BrowserStack, you will need to create a BrowserStack account and obtain an API access key. Once you have your API access key, you can configure Playwright to connect to BrowserStack.
Here are the steps to integrate Playwright with BrowserStack:
1. Create a BrowserStack account and obtain an API access key.
2. Install the BrowserStack Playwright extension.
3. Configure the BrowserStack Playwright extension with your API access key.
4. Write your Playwright tests using the BrowserStack Playwright extension.
5. Run your Playwright tests on BrowserStack using the following command:
```
npx playwright test --browser=browserstack
```
You can find more information on how to integrate Playwright with BrowserStack in the BrowserStack documentation: www.browserstack.com/docs/automate/playwright.
Here are some of the benefits of integrating Playwright with BrowserStack:
*Test on a wide range of browsers and operating systems.** BrowserStack gives you access to over 2,000 browsers and operating systems, so you can test your application on the same browsers and operating systems that your users are using.
*Parallel testing.** BrowserStack allows you to run your Playwright tests in parallel, which can significantly reduce your testing time.
*Test automation tools.** BrowserStack provides a variety of test automation tools, including Selenium, Cypress, and Playwright. This allows you to use the test automation tool that you are most comfortable with.
*Cloud infrastructure.** BrowserStack provides a cloud infrastructure for running your Playwright tests. This means that you do not need to maintain your own test infrastructure.
I hope this helps
@@RaghavPal tried with creating account and api access key but getting below error during execution for browserstack..
Error:browserType.connect: Error: device Descriptors: expected array, got undefined
Any idea how we can resolve this error
The error "Error:browserType.connect: Error: deviceDescriptors: expected array, got undefined" indicates an issue with the device configuration for your BrowserStack test. It suggests that the device configuration is not providing an array of devices, which is required for BrowserStack to connect to the desired devices for testing.
To resolve this error, ensure that the device configuration is properly defined and provides an array of devices. Here's how to address the issue:
1. **Verify Device Configuration:**
- Review your BrowserStack test script or configuration file to ensure that the device configuration is defined correctly.
- Check for typos, syntax errors, or missing information in the device configuration.
- Ensure that the device configuration is providing an array of devices, not a single device object.
2. **Validate BrowserStack Credentials:**
- Double-check your BrowserStack username and access key to ensure they are valid and have the required permissions to access the desired devices.
- If using an access token, verify that the token is generated correctly and has not expired.
3. **Check BrowserStack Device Availability:**
- Confirm that the devices specified in the configuration are available in your BrowserStack account.
- If using a custom device setup, ensure that the devices are properly configured and accessible.
4. **Update BrowserStack Libraries:**
- Check if you are using the latest versions of the BrowserStack libraries or APIs in your test setup.
- Outdated libraries can sometimes cause compatibility issues and lead to connection errors.
5. **Review BrowserStack Documentation:**
- Refer to the official BrowserStack documentation for detailed instructions on device configuration and connection parameters.
- Ensure that you are following the recommended practices for device selection and configuration.
6. **Seek BrowserStack Support:**
- If the issue persists, contact BrowserStack technical support for assistance.
- They can provide specific guidance based on your account and configuration details.
Remember to restart your test execution after making any changes to the device configuration or BrowserStack settings.
@@RaghavPal Thank you so much for this solution...😇
Hello Raghav
In Playwright Inspector Screen I'm not getting the the Target: Playwright
instead of this Im getting Test Runner
How to do it Can you please help me ?
Hi, just compare the steps from this official documentation - playwright.dev/docs/codegen
Hi Raghav, Your recorded steps having comments at each steps however my recorded test does not have any comment. Can you please advise?
Chitranjan
Not sure, pls check and match all steps. It may also be due to new version changes, can check the documentation
Hi , I am facing an issue where the website takes too long to load while executing using playwright and hence the test fails . If you manually open the website the load time is quick . Can you please suggest any solution for this ? Interception
there are strategies to address this issue. One effective approach is to use request interception in Playwright. Try these steps:
1. Request Interception:
- Playwright provides built-in methods for request interception at both the browser context level (`browserContext.route()`) and the page level (`page.route()`).
- By intercepting requests, you can selectively block unnecessary resources, such as images or CSS files, which can significantly improve loading times.
2. Blocking Unnecessary Resources:
- Identify the types of resources that are slowing down your website. Common culprits include images, stylesheets, and third-party scripts.
- Use request interception to selectively block these resources during your tests. For example:
```javascript
await page.route('/*', (route) => {
if (route.request().resourceType() === 'image') {
route.abort(); // Block image requests
} else {
route.continue(); // Allow other requests
}
});
```
3. Service Workers:
- Sometimes slow loading is caused by service workers. If network events appear to be missing, disable service workers in your browser context:
```javascript
const context = await browser.newContext({
serviceWorkers: 'block', // Disable service workers
});
```
4. Optimize Waiting Strategies:
- Use Playwright's built-in waiting mechanisms (`waitForSelector`, `waitForTimeout`, etc.) instead of hard-coded delays.
- Avoid using unnecessary `waitFor` statements, as they can add unnecessary wait times.
5. Parallel Execution:
- Consider running your tests in parallel. Playwright supports parallel execution, which can speed up your test suite.
6. Network Conditions:
- Test your website under different network conditions (e.g., slow 3G, fast 3G, etc.) to simulate real-world scenarios.
- Use Playwright's `context.emulateNetworkConditions()` to set custom network conditions.
7. Page Load Events:
- Ensure that your tests wait for critical page load events (e.g., DOMContentLoaded, load) before proceeding with assertions.
- Use Playwright's `page.waitForLoadState()` to wait for specific load states.
Remember that each website is unique, so experiment with different strategies to find the most effective approach for your specific case.
..
@@RaghavPal thankyou
An error occurs for me when using NPX, any alternatives with NPM?
erro "objectNotFound(npx:String) [], commandNotFoundException
FullyQualifiedErrorId: CommandNotFoundException
Sheyla
The error message you're encountering, "objectNotFound(npx:String) [], CommandNotFoundException", indicates that the npx command is not recognized. Let's address this issue step by step:
1. Install npx:
- The npx package is essential for running commands from the Node.js ecosystem. If it's not installed, you'll encounter this error.
- Open your terminal and run the following command to install npx globally:
```
npm install -g npx
```
- If you encounter a permissions error, prefix the command with sudo:
```
sudo npm install -g npx
```
2. Update Your PATH Environment Variable (macOS/Linux):
- Sometimes, even after installing npx, you might still face issues. In that case, check your PATH environment variable.
- Run the following command to see where your globally installed packages are stored:
```
npm config get prefix
```
- The output will show the path where global packages are stored (usually in the bin directory).
- Update your PATH environment variable to include this path. For example:
- On macOS:
```
export PATH=/usr/local/share/npm/bin:$PATH
```
- On Linux, add the output path to your .bashrc file:
```
echo 'export PATH="/usr/local/share/npm/bin:$PATH"' >> ~/.bashrc
```
3. Reinstall Node.js:
- If the issue persists, consider reinstalling Node.js on your machine.
- During installation, make sure to check the option to add Node.js to your PATH environment variable.
Hopefully, these steps will resolve the npx command issue
--
how do you make playwright know where to take usernames and passwords from to fill in the website we want to test? how do we make them available to playwright?
Hi Mihaela
In Playwright, you can use environment variables to store the usernames and passwords, and then access them in your test script. Here's an example:
Set environment variables for the username and password:
On Windows:
set PLAYWRIGHT_USERNAME=myusername
set PLAYWRIGHT_PASSWORD=mypassword
On Linux/Mac:
export PLAYWRIGHT_USERNAME=myusername
export PLAYWRIGHT_PASSWORD=mypassword
Access the environment variables in your test script:
const username = process.env.PLAYWRIGHT_USERNAME;
const password = process.env.PLAYWRIGHT_PASSWORD;
await page.fill('input[name="username"]', username);
await page.fill('input[name="password"]', password);
This way, the username and password are not hardcoded in your test script and can be changed without modifying the script.
Hi Raghav, Can we automate the desktop application using playwright. If so can you please ping a video
Vinu
No, Playwright is not designed to automate desktop applications. It is a framework for automating web browsers. However, there are other tools available for automating desktop applications, such as SikuliX and Robot Framework.
Sir Can you make a series of Ansible and Ansible Tower and Kubernets EKS
I will do
Hi Raghav, whenever i run the test below error comes, not able to fix, please guide me,
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.
Vimal
The "Error: No tests found" message can be frustrating, but it is usually caused by a simple configuration issue. Let's troubleshoot this together! Here are some steps you can follow to resolve the issue:
1. Check Your Test File Path:
- Ensure that the path to your test files is correct. Double-check the location of your test files and make sure they are accessible.
- If you're using relative paths, ensure that they are relative to the root directory of your project.
2. Naming Convention:
- Make sure your test files follow a consistent naming convention. Playwright looks for files with names ending in `.spec.ts` by default.
- If your test files have a different naming pattern, you can specify the file pattern explicitly when running tests.
3. Configuration:
- Verify your configuration settings. Sometimes, misconfigured settings can lead to this error.
- Check if you have any custom configuration files (e.g., `playwright.config.js` or `.playwrightrc.json`) that might affect test discovery.
4. Escape Special Characters:
- If your test file names contain special characters like "$" or "*", make sure to escape them properly.
- For example, if your test file is named `test$.spec.ts`, you should run it as `npx playwright test test\\$.spec.ts`.
5. Quoting Arguments:
- If your test file path contains spaces or other characters that need quoting, make sure to enclose the path in quotes.
- For example, if your test file is in a folder named "My Tests," run it as `npx playwright test "My Tests/test.spec.ts"`.
6. Update Playwright:
- Ensure you're using an up-to-date version of Playwright. Sometimes, older versions may have issues.
- Update Playwright using `npm install @playwright/test@latest`.
7. Install Browsers and Dependencies:
- Run `npm ci` in your project's root directory to install dependencies.
- Then run `npx playwright install --with-deps` to install browsers and their dependencies.
8. Run Your Tests:
- Finally, execute your tests using `npx playwright test`.
Hopefully, one of these steps will help you resolve the issue.
--
Hi@@RaghavPal , thanks for your detailed reply, I will check and confirm the status.
@@RaghavPal My query was resolved , thanks so much.
Hi Raghav, in my application, I tried to switch to Iframe in playwright record, I am getting error getting target closed while switching to . Can you plz suggest how to proceed further
Hi Durga
When you try to switch to an in Playwright, it is important to ensure that the target is loaded before switching to it. Otherwise, you may encounter the "target closed" error.
Here's an example of how to switch to an using Playwright in TypeScript:
// Assuming you have already launched the browser and created a page object
const frameSelector = '#-id'; // Replace this with the actual selector for the
const frameHandle = await page.waitForSelector(frameSelector);
const frame = await frameHandle.contentFrame();
await page.waitForLoadState();
await frame.waitForLoadState();
await page.bringToFront();
await page.waitForSelector('#element-inside-');
In this example, we first wait for the element to appear on the page using page.waitForSelector. We then get a handle to the using frameHandle.contentFrame() and wait for it to finish loading using frame.waitForLoadState(). Finally, we wait for an element inside the to appear using page.waitForSelector.
Make sure that the is fully loaded before trying to interact with it.
@@RaghavPal Thanks for your reply
Hey Raghav Very good info I am stuck in one of scenario where when i am running my testcase getting error
" 14 |
> 15 | const testData = JSON.parse(fs.readFileSync(`C:\\Playwright automation\\ilm-ui-automation\\src\data\\users.json`, `utf-8`))
| ^
16 |
17 | class LandingPage extends BasePage {
18 | constructor(page) {
at Object. (C:\Playwright automation\ilm-ui-automation\src\pages\landingPage.js:15:32)
at Object. (C:\Playwright automation\ilm-ui-automation\src\testFixtures\fixture.js:3:1)
at Object. (C:\Playwright automation\ilm-ui-automation\src\tests\TC_01_login.test.js:9:1)
Error: No tests found"
Hi Sanket
The error message indicates that there are no tests found in your test file. This could be due to a few possible reasons. Here are some suggestions to help you resolve the issue:
1. Check the test file path: Make sure that the file path you provided is correct and the file exists. Double-check the path `C:\Playwright automation\ilm-ui-automation\src\tests\TC_01_login.test.js` to ensure it is accurate
2. Verify the test function: Ensure that you have defined at least one test function in your test file. The test function should be using a test framework such as Jest or Mocha and have a test assertion within it
3. Check for test runner configuration: If you are using a test runner to execute your tests, such as Jest or Mocha, make sure that the configuration is set up correctly. Check the configuration file (e.g., `jest.config.js` or `mocha.opts`) to ensure that it includes the correct file patterns and settings for test discovery
4. Validate the data file: The error message also suggests an issue with reading the data file `users.json`. Ensure that the file exists in the specified location (`C:\Playwright automation\ilm-ui-automation\src\data\users.json`). Verify the file path and make sure the file is accessible
5. Check for syntax errors: Review your test file, `landingPage.js`, `fixture.js`, and `TC_01_login.test.js`, for any syntax errors or typos that could be causing the tests not to be recognized
By investigating these aspects, you should be able to identify the cause of the "No tests found" error and resolve it accordingly
Hi Raghav, Can you please add more advanced videos in playwright. Thank you!
I will do Kishore
@@RaghavPal Thank you so much!
Hey Raghav thankyou so much for explaining Playwright. But, i think you give the wrong explaination on 20:55. that's all run on chromium. Hope the best for you raghav, all the best for you. Give us the complete explaination on playwright please
Hi Rian, I checked again, I said it will run on all 3 browsers, Let me know if there is any issue, thanks for watching
Happy Teachers day @Raghav sir
Thanks and same to you Asif
Hi Raghav when i try test the recording it doesnt show the recording but says no test found
Error: No tests found
To open last HTML report run:
npx playwright show-report
PS C:\Users\User\Desktop\playwright> npx playwright test
Running 6 tests using 2 workers
6 passed (22.0s)
Error: No tests found
To open last HTML report run:
npx playwright show-report
PS C:\Users\User\Desktop\playwright>
Hi Nomandla
The error message "No tests found" means that Playwright could not find any test files in the current directory. There are a few possible reasons for this:
* The test files are not named correctly. Playwright expects test files to have a name that ends in `.spec.js` or `.spec.ts`.
* The test files are not in the current directory. Playwright will only look for tests in the current directory and its subdirectories.
* The test files are not using the Playwright API. Playwright tests must be written using the Playwright API.
To troubleshoot this error, you can try the following:
* Check the names of the test files to make sure they end in `.spec.js` or `.spec.ts`.
* Make sure the test files are in the current directory or one of its subdirectories.
* Check the code in the test files to make sure they are using the Playwright API.
If you have checked all of these things and you are still getting the error message, then you may need to contact Playwright support for help.
In your case, the error message says that you have 6 tests, but they are not being found. This suggests that the test files are not named correctly or they are not in the current directory. You can try renaming the test files to end in `.spec.js` or `.spec.ts`, or you can move the test files to the current directory. If that doesn't work, then you can try checking the code in the test files to make sure they are using the Playwright API.
I hope this helps
It wasn't clear to me, why on minute 20 did you have to require {Chromium} from @playwright/test ?? I thought that was the default.
Hi, when we install playwright, we get all the required browser libraries
When I am recording and saving in a file I am getting "Cannot find module 'playwright' " error message. In the terminal is shows as following:
1 | const { chromium } = require('playwright');
| ^
2 |
3 | (async () => {
4 | const browser = await chromium.launch({
at Object. (C:\Playwrite_Automation\tests
ecord_demo.spec.js:1:22)
Error: No tests found
Can you please help me with this issue. Thanks in advance
Hi Swati
The error message "Cannot find module 'playwright'" means that the Playwright module is not installed on your system. You can install Playwright by running the following command:
```
npm install -g playwright
```
Once Playwright is installed, you should be able to run your code without any errors
Here are some possible reasons why you might be getting the error message "Cannot find module 'playwright'":
* Playwright is not installed on your system.
* Playwright is installed, but it is not in your PATH environment variable.
* You are trying to use a Playwright function that is not available in the current version of Playwright
If you have checked all of these things and you are still getting the error message "Cannot find module 'playwright'", you can post a question on the Playwright forum or on the Playwright issue tracker
Here are some additional things to check:
* Make sure that you are using the correct syntax for importing the Playwright module.
* Make sure that the Playwright module is installed in the same directory as your code.
* Make sure that the Playwright module is compatible with the version of Node.js that you are using
@@RaghavPal Thanks Raghav
Could you help me ? When I tryed to run my tests is not openning the browser, just showing
"PS C:\Project\Playwrigth_Automation> npx playwright test .\tests\Demo1.spec.js --headed
Error: No tests found
To open last HTML report run:
npx playwright show-report
"
and when I open the report is blank
Hi André
The error message "No tests found" typically indicates that there are no test cases detected in the specified test file(s). There are a few things you can check to troubleshoot this issue:
1. Verify the test file path: Make sure that the path to your test file, `.\tests\Demo1.spec.js`, is correct and that the file exists in the specified location. Double-check for any typos or incorrect file extensions.
2. Check the test file content: Ensure that the test file contains valid test cases written in the Playwright test syntax. Each test case should be defined using the `test` function provided by Playwright. Here's an example of a valid test case:
```javascript
const { test, expect } = require('@playwright/test');
test('My Test', async ({ page }) => {
// Test actions and assertions
});
```
Make sure that your test file follows a similar structure with actual test cases defined.
3. Verify the Playwright test framework setup: Ensure that you have set up the Playwright test framework correctly in your project. This includes installing the necessary dependencies and configuring the test runner.
To set up Playwright test framework, follow these steps:
- Initialize a new Node.js project: `npm init -y`
- Install the Playwright test package: `npm install @playwright/test`
- Write your test cases in separate test files (e.g., `.spec.js` files).
- Configure the test runner in the `package.json` file:
```json
"scripts": {
"test": "playwright test"
}
```
Make sure you have followed these steps correctly and that the necessary dependencies are installed.
If you've verified all of the above and are still experiencing issues, it's possible that there may be an error or misconfiguration in your test file(s). Check for any syntax errors or other issues that might prevent the tests from being recognized.
Regarding the blank report, it suggests that the test execution did not generate any test results. Double-check that your test file(s) contain valid test cases and that the test execution was successful without any errors or exceptions
@@RaghavPal thanks for your help
1 - is ok
2 - I change to import { test, expect } from '@playwright/test';
3 if I do " npx playwright test" , works, but if I put a specific path dosen't works.
will need to check if you are giving the path and syntax correctly, check for slashes,
Also check the configuration file. Check if there's a configuration file (e.g., playwright.config.js or playwright.config.ts) present in the specified path or the current working directory. The configuration file could define the test file patterns and other settings.
hi ,when i type npx playwright codegen --target *** what kind of language should i write down because im using typescript and it doesnt appear as a language
Hi Keivi
When you type `npx playwright codegen --target *` and TypeScript doesn't appear as a language, you can write `ts` as the language. This will generate TypeScript code for your tests.
For example, the following command will generate TypeScript code for a test that opens the Google homepage:
```
npx playwright codegen --target ts www.google.com
```
The generated TypeScript code will be saved in a file called `google.test.ts`. This file can then be run using the `npx playwright test` command.
Here is a list of the supported languages for the `playwright codegen` command:
* `js` - JavaScript
* `ts` - TypeScript
* `go` - Go
* `java` - Java
* `python` - Python
* `csharp` - C#
* `swift` - Swift
* `kotlin` - Kotlin
I hope this helps
@@RaghavPal npx playwright codegen --target ts -o ./tests/record2_demo.spec.ts and it show Unsupported language: 'ts'.....even when i type 'ts' even when i type 'typescript' this is the message appeared
@@RaghavPal even when i type npx playwright codegen --h it shows me these languages --target language to generate, one of javascript, playwright-test, python, python-async, python-pytest, csharp, csharp-mstest, csharp-nunit, java (default: "playwright-test")......i've tried with playwright-test and it works but im not sure if this is the language to use for typescript
will need to check some online examples and try
I type npx playwright codegen --device="iPhone 11" and i get "Error: Device descriptor not found: 'iPhone', available devices are:" and i type any of those and dont work :( what could be the problem?
Fabrizio
Let's troubleshoot this together
1. Device Descriptors Issue:
The error message you received indicates that the device descriptor for "iPhone 11" is not recognized. This could be due to a few reasons:
- Incorrect Device Name: Make sure you're using the correct device name. For example, it should be "iPhone 11" (with proper capitalization and spacing).
- Playwright Version: Ensure that you're using an up-to-date version of Playwright. Outdated versions may not support certain device descriptors.
2. Workaround for Windows:
There's a known issue related to quotes and spaces in NPX on Windows. If you're using Windows, try the following workaround:
- Install NPM v7 (which handles directories with spaces correctly):
```
npm install -g npm@7
```
- Then, run your Playwright codegen command again.
3. Alternative Approach:
Instead of specifying the device directly in the command, you can use the Playwright Inspector to record your interactions and generate the test code. Here's how:
- Run the following command to open the Playwright Inspector:
```
npx playwright codegen
```
- Interact with the website you want to test in the browser window.
- Stop recording when you're done, and copy the generated test code into your editor.
Remember to adjust the steps based on your operating system and Playwright version
Hi Raghav, there's a typo in the quiz. Within the second answer from this question: Command to use codegen test generator to record on firefox browser. The second answer is: npx playwright codegen --browse=ff But this has te be: npx playwright codegen --browser=ff
Which quiz is that, please share
@@RaghavPal The quiz that is included by this course.
ok, corrected it. thanks
why should we give the filename as .spec.js? what is the difference between .spec.js and .js?
Hi Sindhura,
In Playwright, it is common practice to name test files with a suffix of ".spec.js" to indicate that they contain test specifications. The ".js" extension indicates that the file is a JavaScript file, but using ".spec.js" helps to differentiate test files from other JavaScript files in a project.
The ".spec" in the filename refers to "specification," which is a term used in testing frameworks to describe the definition of what a test should accomplish. A test specification defines the behavior that a test should verify and the expected results.
In addition, some testing frameworks or tools use certain naming conventions to automatically detect and run test files. For example, Jest, a popular JavaScript testing framework, will automatically run any file that matches the pattern **/__tests__/*.js?(x) or **/?(*.)+(spec|test).[tj]s?(x).
So, by naming test files with the ".spec.js" suffix, it helps to organize and identify test files, and it also allows testing frameworks or tools to automatically detect and run those files as tests.
@@RaghavPal Thanks so much.. it's clear now :-)
Hi raghav this is ranga i want to learn playwright , Actually am familiar with java so can i prefer playwright with javascript or java
Both can be used, you will be okay with JavaScript. Just follow the sessions and you will get it, I have created it for complete beginners step by step
@@RaghavPal thank you so much raghav mean while is it possible to u create a series of api with playwright ?
I will plan
I did not get the comments when recording with codegen in playwright inspector why?
Hi Sandeep,
By default, the Playwright Inspector does not record comments when generating code using the codegen feature. This is because the Inspector is primarily designed to help users visually inspect and debug web pages, and comments may not be useful in that context.
However, if you want to include comments in your generated code, you can do so by manually adding comments to the script as you record it using the Inspector. Here's an example:
Open the Playwright Inspector and start recording a new script.
Perform the actions you want to record in the browser.
As you perform each action, switch to the code view in the Inspector and add comments to the generated code using the // syntax.
Continue recording and adding comments until you have recorded all the actions you need.
When you're finished, stop the recording and export the script using the codegen feature.
The comments you added in step 3 will be included in the generated code.
Alternatively, if you prefer to generate the code using the playwright-cli tool, you can use the --save-storage option to include comments in the generated code. This option saves a JSON file with the recording metadata, including comments, which can be used to generate code later. Here's an example command:
npx playwright-cli codegen --browser chromium --save-storage=recording.json my_script.js
In this example, the --save-storage option saves the recording metadata to a file named recording.json. You can then use the --load-storage option to load the metadata and generate the code with comments:
npx playwright-cli codegen --browser chromium --load-storage=recording.json my_script.js
Note that the --load-storage option is only available in Playwright version 1.17.0 or later
Hi,
Following the same steps but getting result as 0 tests using 0 workers.
Please help me with this.
Hi Kajal, what command are you using
Hope you are running the command from the project test folder
example
npx playwright test loginPage.spec.ts
github.com/microsoft/playwright/issues/13092
1:30
3:00 codegen option of npc - 2 windows are opened
3:25 Playwright *inspector*
4:25
thanks for adding the timestamps 🙏🏻
what can we do if we want to record Api test
Hi Gaurav
To record API tests in Playwright, you can follow these steps:
1. Install the Playwright API client.
2. Create a new project.
3. Create a new file called `api.spec.js`.
4. In the `api.spec.js` file, import the Playwright API client.
5. Write a test that makes an API call.
6. Run the test.
Here is an example of a Playwright API test:
```
import { HttpClient } from "@playwright/test";
test("Make an API call", async () => {
const client = new HttpClient();
const response = await client.get("www.google.com");
expect(response.status).toBe(200);
});
```
This test makes an API call to the Google homepage and verifies that the status code is 200.
To run the test, you can run the following command:
```
npx playwright test api.spec.js
```
This will run the test and print the results to the console.
Here are some additional things to keep in mind:
* The Playwright API client is a JavaScript library that you can use to make API calls.
* The `HttpClient` class in the Playwright API client provides methods for making different types of API calls.
* The `test` function in the Playwright API client is used to write API tests.
* The `expect` function in the Playwright API client is used to verify the results of API calls.
I hope this helps!
can you please make tutorial on automating Image captcha?
Please check this - th-cam.com/video/QIYbr81dJGQ/w-d-xo.htmlsi=vFCQRfxtlT7L05xV
My script shows no tests found. Why? please help
Hi Swati,
If your Playwright script is not being recognized by your test runner and is showing "no tests found", there are a few things you can check:
Make sure that your test files are named with the ".test.js" or ".spec.js" extension. Test runners like Jest and Mocha require this naming convention in order to automatically detect your tests.
Check that your test files are located in the directory that your test runner is configured to search for tests. By default, most test runners will search for tests in a folder called "test" or "tests" in the root of your project. If your tests are located in a different folder or subdirectory, you may need to configure your test runner to look in that directory.
Ensure that your test functions are correctly defined and exported. In order for your test runner to recognize your test functions, they must be defined using the correct syntax and exported using the "module.exports" or "export" statement. For example:
const { test, expect } = require('@playwright/test');
test('my test', async () => {
// test code here
expect(true).toBeTruthy();
});
If you are using a custom test runner or configuration, make sure that it is correctly configured to work with Playwright. Depending on the test runner, you may need to install and configure additional plugins or modules in order to run Playwright tests.
If you have checked these things and are still experiencing issues, please provide more details about your setup and test runner so that we can better assist you.
I am always getting error "NO test Found" when i try to run the test. what could be the reason
Shanawaz
There are a few reasons why you might be getting the error "No test found" when running Playwright tests:
*Your test files are not in the correct directory.** Playwright tests must be located in the `tests` directory.
*Your test files do not have the correct extension.** Playwright tests must have the `.spec.js` or `.spec.ts` extension.
*Your test files are not named correctly.** Playwright tests must start with the word `test` or `suite`.
*You are not running the Playwright test runner.** To run Playwright tests, you must use the Playwright test runner. You can run the Playwright test runner using the following command:
```
npx playwright test
```
If you are still getting the error "No test found" after checking all of the above, you can try the following:
*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.
Here are some additional tips for running Playwright tests:
* Make sure that you have the latest version of Playwright installed.
* Make sure that you have Node.js installed.
* Make sure that you are running the Playwright test runner from the correct directory.
* Make sure that your test files are in the correct directory and have the correct extension.
* Make sure that your test files are named correctly.
I hope this helps
@RaghavPal
Thanks for the detailed answers, I have checked all of them, however the solution was simple, that the syntax to run test was to use forward slash rather than backwards while giving the location of the test files. That has run the test.
Don't know what could be the reason..
okay, there are multiple reasons for this issue, great it is solved now
@@RaghavPal Thank you for the great videos, it is a life savior..
18:31 Hello Sir why you have a comment when you run codegen as record
it gets generated with codegen.. not sure if it happens in latest versions too
@@RaghavPal not generating in my case npm version 10.7.0
Ok, you can use the --comments flag when running the playwright codegen command. For example:
npx playwright codegen --comments
Hello Raghav,
PS D:\Automation Tools\Playwright_automation> npx playwright test .\tests
ec_demo.spec.js --project chromium --headed
Running 0 tests using 0 workers
=================
no tests found.
why my tests are not running
Pls check if this helps github.com/microsoft/playwright/issues/13092
Hi Sir, This video is very helpful for me because I am beginner of Playwright. I watched this video and try to practice. But after ran nothings is happened and no error message is occurring. when I copy this script from recorded screen then there is no option to copy as Playwright Test. I am not able to see my result in Headed mode. I need your advice Sir on this.
After ran this below message is occur
Running 0 tests using 0 workers
=================
no tests found.
Hi Arijit,
Here are a few things you can try:
Check if you have set up Playwright and its dependencies correctly
Ensure that you have written the tests correctly. You can refer to the Playwright documentation for examples and syntax guidance.
Verify that the tests are in the correct directory and are being picked up by the test runner. You can use the command ls or dir to list the contents of the directory where your tests are located.
If you are still unable to run the tests, try running the tests in non-headed mode to see if any error messages are being printed to the console.
Make sure that the test code is being executed correctly and that there are no syntax errors in the code. You can use a linter or a code editor to check for syntax errors.
@@RaghavPal Thank you sir. I will follow your instructions and update you shortly.
Thanks
Arijit Mohanty
Hi Sir, I have tried and check all the dependencies but from Terminal I am not able to run the script. I tried with Testing menu and Ran the script and getting the result. In my first script this will be run for all Browser but this only run in Chromium. Kindly give your valuable suggestion Sir.
thanks
Arijit
Hi Arijit,
Try some examples with the official documentation and check again
@@RaghavPal Thanks sir for your advice. I tried with multiple examples but from terminal with file name test was not run and no error message is occured. Sorry for late reply.
10:40
11:50 all options of *codegen*
Thanks for adding timestamps
Not so urgent question but my recording doesn't have any comments generated, in case you know already on top of your head. Thanks.
Sandip
If your Playwright recordings are not generating comments, there are a few things to consider:
1. Change in Behavior:
- Starting from Playwright version 1.27, comments are no longer automatically generated during recording.
- The assumption is that the recorded actions are self-explanatory, so comments were removed².
2. Self-Documenting Actions:
- Since the recorded actions should be clear and descriptive, comments are considered unnecessary.
- If you find that your recorded actions are not self-documenting, consider manually adding comments to your test code.
3. Manual Commenting:
- After recording your test, open the generated test file (e.g., `test-1.spec.ts`) in your code editor (such as VS Code).
- Review the recorded actions and add comments where needed to explain the purpose or context of specific steps.
- Comments can help other team members understand the test logic and improve maintainability.
Remember that while comments are helpful for readability, well-named actions and descriptive test steps are equally important.
@@RaghavPal thanks lot Raghav 🙏🏻
You are too good!!
20:55 for those that are getting a syntax error for the last line, my version 1.42.1, it wants two closed parentheses:
}));
Thanks for adding Andrei
Quiz score 9/10😅
Great Ayush, Keep learning
const config = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 30 * 1000,
github.com/microsoft/playwright/issues/13092
8/10 ... missed the Firfox and iphone
Great, all the best for next Bhushan
my score is 8/10. wrong at browser and script question. thank
Great score Anto
your welcome@@RaghavPal
Hi Raghav, When I run "npx playwright codegen --target javascript -o .\tests
ecorddemo.spec.js" my code from the codegen does not get saved in the target file
Hi Pallavi
There are a few reasons why your code from the codegen might not be getting saved in the target file when you run `npx playwright codegen --target javascript -o .\tests
ecorddemo.spec.js`.
*The target file might not exist* The target file must exist before you can run the codegen command. If the target file does not exist, the codegen command will not create it
*The target file might be opened in a text editor* If the target file is opened in a text editor, the codegen command will not be able to write to the file. Close the target file in any text editors that might be open before running the codegen command
*The codegen command might be interrupted* If the codegen command is interrupted, it might not be able to finish writing to the target file. Make sure that the codegen command has finished running before closing the terminal window
If you have tried all of these things and your code from the codegen is still not getting saved in the target file, you can try the following:
*Run the codegen command again* Sometimes, running the codegen command again can fix problems with the target file.
*Check the permissions on the target file* The target file must have write permissions for the codegen command to be able to write to it. Check the permissions on the target file and make sure that they are correct.
*Contact Playwright support* If you have tried all of these things and you are still having problems, you can contact Playwright support for help
@@RaghavPal Thanks! I tried all of the things, issue still exists
but just one thing I would like to ask you is how to check the permissions on the target file?
Pallavi
To check the permissions on a file, you can use the `ls` command with the `-l` option. For example, to check the permissions on the file `.\tests
ecorddemo.spec.js`, you would use the following command:
```
ls -l .\tests
ecorddemo.spec.js
```
To check the permissions on a file in Windows, you can use the dir command with the /a option. For example, to check the permissions on the file .\tests
ecorddemo.spec.js, you would use the following command:
dir /a .\tests
ecorddemo.spec.js
The permissions for a file are represented by a combination of characters. Each character represents a different permission. The following table shows the meaning of the characters:
Character | Meaning
---|---
r | Read permission
w | Write permission
x | Execute permission
- | No permission
For example, the permissions `rw-r--r--` mean that the owner of the file has read and write permissions, the group has read permission, and other users have read permission.
If the target file does not have write permissions, the codegen command will not be able to write to the file. To change the permissions on a file, you can use the `chmod` command. For example, to change the permissions on the file `.\tests
ecorddemo.spec.js` so that the owner has read and write permissions, the group has read permission, and other users have no permissions, you would use the following command:
```
chmod 644 .\tests
ecorddemo.spec.js
```
For Windows
icacls .\tests
ecorddemo.spec.js /grant "Administrators:(OI)(CI)(M)"
The icacls command takes three arguments: the file name, the user or group name, and the permission. The user or group name is the user or group that you want to grant the permission to. The permission is the permission that you want to grant to the user or group.
The permission M means that the user or group has write permission.
The `chmod` command takes three arguments: the mode, the owner, and the group. The mode is a combination of characters that represent the permissions for the owner, group, and other users. The owner is the user who created the file. The group is the group that the file belongs to.
The mode `644` means that the owner has read and write permissions, the group has read permission, and other users have no permissions
npx playwright test .\demo-cdp
ecord1_demo.spec.jsError: No tests found
Đại
Please check by changing back slashes \ in the path of test file with forward slashes /. As you type few characters press tab so that it can auto complete and you don't make any typing errors
Hi Sir,
This is Rajkumar
After recording test in playwright and copying the code by using the command ---
npx playwright codegen --target javascript -o tests/record2_example.js
The following error is came....
***********************************************************************************
PS C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation> npx playwright test tests/record2_demo.spec.js --project=chromium --headed
Running 0 tests using 0 workers
Error: Cannot find module 'playwright'
Require stack:
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation\tests
ecord2_demo.spec.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib\common\transform.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib\common\testType.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib\common\test.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib
eporters\multiplexer.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib
unner
eporters.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib
unner
unner.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\lib\cli.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\playwright-core\lib\cli\cli.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\playwright-core\cli.js
- C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation
ode_modules\@playwright\test\cli.js
at record2_demo.spec.js:1
> 1 | const { chromium } = require('playwright');
| ^
2 |
3 | test('record demo 2',async () => {
4 | const browser = await chromium.launch({
at Object. (C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation\tests
ecord2_demo.spec.js:1:22)
Error: No tests found
To open last HTML report run:
npx playwright show-report
PS C:\Users\DELL\Documents\My Files\Playwright\Playwright_Automation>
*********************************************************************************
Please let me know why?
And "npx playwright test .\tests
ecord1_demo.spec.js" this path in command is not working...
instead...
"npx playwright test tests/record1_demo.spec.js" is working. But why I don't know.
Please give clarity.....
🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏🙏
Hi Rajkumar,
The error message "Cannot find module 'playwright'" suggests that Node.js is unable to find the Playwright module that is required to run the test. This could be because the module is not installed, or it is not included in the project's dependencies.
To resolve this error, make sure that you have installed Playwright in your project's dependencies. You can install it by running the following command in your project directory:
npm install playwright --save-dev
This will install Playwright as a development dependency and add it to the project's package.json file.
Regarding the path in the command "npx playwright test .\tests
ecord1_demo.spec.js", the backslash character "" is used as an escape character in many programming languages, including JavaScript. This means that when you use it in a file path, you need to escape it or use a forward slash instead. That's why the command "npx playwright test tests/record1_demo.spec.js" is working