In this step-by-step guide, we will show you how to create your first successful e2e Playwright test for an Angular 14 project.
Step 0 (optional): Start Cloud Desktop – or use your own environment
If you need a development environment, you can connect to our Developer’s Cloud Desktop. Simply click on the image below and launch the environment by clicking on the WebStorm Cloud Desktop button (bring your own license or get a free 30-day trial from JetBrains).
Alternatively, you also can use the free VS Code Cloud Desktop. Or you use your own development environment and install NPM if needed.
You can increase the resolution by clicking on the Display icon on the desktop:
If you are running your development environment on a Full HD screen, we recommend 1920×1056 and running your browser in full-screen mode. This will avoid the need for scrollbars.
Step 1: (Re-) Install Angular
A relatively old version of angular is installed in the Developer’s Cloud Desktop, currently. The easiest way to upgrade it is to re-install it. For that, open a terminal and issue the following two commands:
npm remove -g @angular/cli npm install -g @angular/cli
We can check the version with the ng version
command:
Step 2: Create a Hello World Project
Let us now create a new hello world project
ng new playwright-hello-world
You are asked some questions. In my case, I have chosen Angular routing: Yes
and stylesheet format: SCSS
. However, in this Hello World program, we will not manipulate CSS anyway.
Let us enter the newly-created directory and start the server:
cd playwright-hello-world ng serve
We optionally can connect to the server by opening http://localhost:4200 in a browser on the developer’s cloud desktop:
However, this is not needed for our first Playwright test.
Step 3: Install Playwright
We now choose to install Playwright as a dev-dependency in our project. In addition,
npm install @playwright/test --save-dev npx playwright install chromium
Playwright needs to know how to start a browser. By default, it will not find any installed browser on the system. The simplest way to circumvent that problem is to let Playwright install its own browser:
npx playwright install chromium
Step 4: Configure Playwright
We have seen that Playwright is confused if it finds any karma or jest spec files, and the test.js
file. For details see the appendix chapter below.
In order to fix this behavior, we create a minimalistic Playwright configuration file on project root:
// playwright.config.ts import type { PlaywrightTestConfig } from '@playwright/test'; const config: PlaywrightTestConfig = { testDir: './e2e-playwright', }; export default config;
Here, we have told Playwright that it should search for spec files in the e2e-playwright
directory. With that, it will not be confused by karma files anymore.
Step 5: Create a first Playwright spec file
In the Playwright configuration file above, we have specified that all Playwright tests will be located in the e2e-playwright
directory. Therefore, let us create that folder and place a simple Playwright test into that folder:
// create test folder mkdir e2e-playwright // create an example spec file: cat <EOF > e2e-playwright/example.spec.ts import { test, expect } from '@playwright/test'; test('basic test', async ({ page }) => { await page.goto('https://playwright.dev/'); const title = page.locator('.navbar__inner .navbar__title'); await expect(title).toHaveText('Playwright'); }); EOF
Step 6: Run the Playwright Test
Now the test should be successful:
playwright test
We should see something like:
Step 7 (optional): Run the Test in non-headless Mode
We have not seen that yet, but under the hood, the installed Chromium browser will be started. We will be able to verify this by configuring the tests to be performed in a non-headless mode:
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: './e2e-playwright',
use: {
headless: false
},
};
export default config;
If we now re-run the test, a browser will be started visibly:
playwright test
Step 8: Test your own Application
You might have noticed that the „hello world“ Playwright test above did not test your own application. Instead, an external URL was tested.
Let us now create a first test that will test our own application. Once again, we start the application, if not already done:
npm run start # or ng serve
At the moment, our application consists of the default page provided by Angular 14, which can be seen, if we navigate to http://localhost:4200/
:
With F12 in a Chrome browser, we can see, that the locator of the title playwright-hello-world
is body > app-root > div.content > div.card.highlight-card.card-small > span
. In order for the locator not to be too implementation-specific, let us choose div.card.highlight-card.card-small > span
only.
With this information, we can create a Playwright test that tests our application. Let us create following file within the e2e-playwright
directory:
// project-url-example.spec.ts // // Test your own Application // import pkg from '../package.json'; import { test, expect } from '@playwright/test'; test('Main page find title', async ({ page }) => { await page.goto('http://localhost:4200/'); const title = page.locator('div.card.highlight-card.card-small > span'); await expect(title).toHaveText(`${pkg.name} app is running!`); });
Note: if you want to get rid of the TS-Lint complaints your IDE might show, you should add the following two lines into the compilerOptions section of the tsconfig.json file located in the project root:
// tsconfig.json ... "compilerOptions": { "resolveJsonModule": true, "esModuleInterop": true,
Now let us run the playwright test.
playwright test
If all went well, the output will look like follows:
Step 9 (optional): Automatically spin up the Server (suitable for Continuous Integration)
Note that the application must be up and running for the test to succeed. That is, why we have manually run the command npm run start
above. Can we automate this, e.g. for usage in a continuous integration pipeline?
Yes, we can:
// playwright.ci.config.ts import type { PlaywrightTestConfig } from '@playwright/test'; const config: PlaywrightTestConfig = { testDir: './e2e-playwright', webServer: { command: 'npm run start', reuseExistingServer: true, url: 'http://localhost:4200/' }, use: { headless: true }, }; export default config;
Here, we have added the webServer section that specifies the command to start the application server, if the server is not already running on port 4200
.
Now let us stop the manually started server and run the Playwright tests again:
playwright test
If the web server was stopped before, th
Notice the WebServer logs before the actual tests are started if the server is not already running.
Let us double-check the other case, where the server is running in the background continuously:
npm run start
In a second terminal, we run the tests again:
playwright test
In this case, the startup of the web server is skipped, which speeds up the setup time:
Since the setup time is optimized in the mode, this mode is best suitable for the local development of Playwright scripts.
Step 10: Debugging with Playwright Inspector
There is a simple method how to debug Playwright scripts step by step: just start the Playwright Inspector by using the --debug
option:
playwright test --debug
This will spin up the Playwright Inspector and it will pause on the first Playwright command; the page.goto command in this case:
We now can debug the Playwright script step-by-step by clicking the „step over“ button:
In our case, our application will load and the located HTML element is highlighted in the browser:
Step 11 (optional): Debugging using the „Playwright Test for VSCode“ Plugin
Playwright Inspector comes with Playwright and there was no need to install anything. It helped to test our Playwright scripts step-by-step. However, Inspector does not offer a convenient possibility to watch the values of the variables used.
A little Internet research has shown that there is a free plugin for Visual Studio Code that will help us here.
In a recent version of Visual Studio Code, install the plugin „Playwright Test for VSCode“:
Now open the Folder, where our project is located and wait for 2 to 3 minutes until the indexing has finished. After that, you should see a green triangle left of the playwright test:
Here, you can either run that single test, or you can debug the test by setting a breakpoint left of the await line and by right-clicking on the triangle:
VS Code run Playwright, which will start the browser. The execution is paused at the previously set breakpoint:
We now can step through the code as we are used to when using an integrated development environment:
Moreover, the IDE allows us to watch the values of any object.
Step 12: Tracing after failed tests
In case of failed tests, Playwright offers extensive tracing capabilities. After a failed test, run the following command and select the zip file found on <playwright-dir>/reports/html/data
playwright show-trace
In the actions pane, navigate through the steps. In the middle main window, you will see the content of the browser for each step. The great thing about the tool is. that those are no screenshots, but they are snapshotted browser contents that can be browsed by right-click and choosing „Investigate“. Chrome will open the dynamic HTML content of the page.
Note: you might need to repeat the right-click a second time in order to be navigated to the correct position within the dynamic HTML content of the snapshot.
Appendix: Error message in case of a missing playwright.config.ts File
Problem
We have seen that Playwright is confused if it finds any karma or jest spec files, and the test.js
file. In our case, we have seen error messages like follows, when we run playwright test
without telling Playwright where to search for specification files:
// error messages seen on a fresh Angular project // when we run `playwright test` without playwright.config.ts file: $ playwright test Running 0 test using 0 worker Error [ERR_REQUIRE_ESM]: require() of ES Module /headless/git/playwright-hello-world/node_modules/@angular/core/fesm2015/testing.mjs not supported. Instead change the require of /headless/git/playwright-hello-world/node_modules/@angular/core/fesm2015/testing.mjs to a dynamic import() which is available in all CommonJS modules. at src/app/app.component.spec.ts:3 1 | import { TestBed } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; > 3 | import { AppComponent } from './app.component'; | ^ 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async () => { at Object. (/headless/git/playwright-hello-world/src/app/app.component.spec.ts:3:16) at Module.A._compile (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/utilsBundleImpl.js:16:994) at Object.t..tu._extensions. (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/utilsBundleImpl.js:16:1010) at Loader._requireOrImport (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/loader.js:276:14) at Loader.loadTestFile (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/loader.js:163:18) at Runner._runFiles (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/runner.js:289:44) at Runner._run (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/runner.js:224:23) at async TimeoutRunner.run (/headless/git/playwright-hello-world/node_modules/playwright-core/lib/utils/timeoutRunner.js:53:14) at async raceAgainstTimeout (/headless/git/playwright-hello-world/node_modules/playwright-core/lib/utils/timeoutRunner.js:113:15) at async Runner.runAllTests (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/runner.js:182:20) at async runTests (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/cli.js:162:18) at async Ai. (/headless/git/playwright-hello-world/node_modules/@playwright/test/lib/cli.js:70:7) ReferenceError: Zone is not defined at node_modules/zone.js/bundles/zone-testing.umd.js:101 99 | return Error.stackTraceLimit > 0; 100 | } > 101 | Zone['longStackTraceZoneSpec'] = { | ^ 102 | name: 'long-stack-trace', 103 | longStackTraceLimit: 10, 104 | // add a getLongStackTrace method in spec to at /headless/git/playwright-hello-world/node_modules/zone.js/bundles/zone-testing.umd.js:101:5 at /headless/git/playwright-hello-world/node_modules/zone.js/bundles/zone-testing.umd.js:18:9 at Object. (/headless/git/playwright-hello-world/node_modules/zone.js/bundles/zone-testing.umd.js:19:3) at Object. (/headless/git/playwright-hello-world/src/test.ts:3:1) ================= no tests found. =================
Even if there are valid Playwright tests, Playwright will skip them due to those errors.
Solution
In order to fix this behavior, we create a minimalistic Playwright configuration file on project root:
// playwright.config.ts import type { PlaywrightTestConfig } from '@playwright/test'; const config: PlaywrightTestConfig = { testDir: './e2e-playwright', }; export default config;
Here, we have told Playwright that it should search for spec files in the e2e-playwright
directory. With that, it will not be confused by karma files anymore.
References
- Find this code on GitHub: https://github.com/vocon-it/playwright-hello-world-angular
I loved as much as youll receive carried out right here The sketch is tasteful your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike
Its like you read my mind You appear to know a lot about this like you wrote the book in it or something I think that you could do with some pics to drive the message home a little bit but instead of that this is fantastic blog An excellent read I will certainly be back
Hi i think that i saw you visited my web site thus i came to Return the favore Im attempting to find things to enhance my siteI suppose its ok to use a few of your ideas
Somebody essentially help to make significantly articles Id state This is the first time I frequented your web page and up to now I surprised with the research you made to make this actual post incredible Fantastic job
I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers
Thanks I have just been looking for information about this subject for a long time and yours is the best Ive discovered till now However what in regards to the bottom line Are you certain in regards to the supply
I loved as much as you will receive carried out right here The sketch is attractive your authored material stylish nonetheless you command get got an impatience over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike
Fantastic beat I would like to apprentice while you amend your web site how could i subscribe for a blog site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear concept
Normally I do not read article on blogs however I would like to say that this writeup very forced me to try and do so Your writing style has been amazed me Thanks quite great post
Magnificent beat I would like to apprentice while you amend your site how can i subscribe for a blog web site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear idea
PLEASE HELP ME
My name is Aziz Badawi, I’m 27 year old man from Palestine. Our town has recently evacuated due
to bombardments by Israel, now I am staying at a shelter with my 6 year old daughter Nadia. My wife is
dead and I’m the only one left to take care of my daughter as we are not allowed to depart to my parents house
in Nablus, she is sick with a congenital heart defect and I have no way to afford the medicine she needs anymore.
People here at the shelter are much in the same conditions as ourselves…
I’m looking for a kind soul who can help us with a donation, any amount will help even 1$ we will
save money to get her medicine, the doctor at the shelter said if I can’t find a way to get her the
medication she needs her little heart may give out during the coming weeks.
If you wish to help me and my daughter please make any amount donation in bitcoin cryptocurrency
to this bitcoin wallet: bc1qcfh092j2alhswg8jr7fr7ky2sd7qr465zdsrh8
If you cannot donate please forward this message to your friends, thank you to everyone who’s helping me and my daughter.
Greetings, I noticed that you visited my website; therefore, I am returning the favor by suggesting that I utilize some of your ideas in an effort to improve it.
Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content
My brother suggested I might like this blog He was totally right This post actually made my day You can not imagine simply how much time I had spent for this info Thanks
Somebody essentially help to make significantly articles Id state This is the first time I frequented your web page and up to now I surprised with the research you made to make this actual post incredible Fantastic job
The Beatles – ??????????? ?????????? ???-??????, ?????????????? ? 1960 ???? ? ?????????. ?? ?????? ????? ???????? ????? ? ??????? ???????? ??????? ?? ??????? ????????. ????? ?? ?????? ?????: „Hey Jude“, „Let It Be“, „Yesterday“, „Come Together“, „Here Comes the Sun“, „A Day in the Life“, „Something“, „Eleanor Rigby“ ? ?????? ??????. ?? ?????????? ?????????? ?????????????, ???????? ??????? ? ?????????????? ? ?????, ??? ??????? ?? ????? ?? ????? ??????????? ????? ? ??????? ??????. ?????? 2024 ???? ??????? ?????? ? ??????? ????????? mp3.
Over the last week I eagerly started following this phenomenal website, they share fabulous content with visitors. The site owner excels at educating customers. I’m excited and hope they keep up their awesome work!
greate post i love very goood…
very informative article men keep posting..
wow men thats great very nice post..
men thats great very good..
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Fantastic beat I would like to apprentice while you amend your web site how could i subscribe for a blog site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear concept
obviously like your website but you need to test the spelling on quite a few of your posts Several of them are rife with spelling problems and I to find it very troublesome to inform the reality on the other hand Ill certainly come back again
Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task
What a fantastic resource! The articles are meticulously crafted, offering a perfect balance of depth and accessibility. I always walk away having gained new understanding. My sincere appreciation to the team behind this outstanding website.
Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do so Your writing taste has been amazed me Thanks quite nice post
I just could not leave your web site before suggesting that I really enjoyed the standard information a person supply to your visitors Is gonna be again steadily in order to check up on new posts
of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again
Hi my loved one I wish to say that this post is amazing nice written and include approximately all vital infos Id like to peer more posts like this
What i do not understood is in truth how you are not actually a lot more smartlyliked than you may be now You are very intelligent You realize therefore significantly in the case of this topic produced me individually imagine it from numerous numerous angles Its like men and women dont seem to be fascinated until it is one thing to do with Woman gaga Your own stuffs nice All the time care for it up
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
you are in reality a just right webmaster The site loading velocity is incredible It seems that you are doing any unique trick In addition The contents are masterwork you have performed a wonderful task on this topic
Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem
Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content
you are truly a just right webmaster The site loading speed is incredible It kind of feels that youre doing any distinctive trick In addition The contents are masterwork you have done a great activity in this matter
I have been surfing online more than 3 hours today yet I never found any interesting article like yours It is pretty worth enough for me In my opinion if all web owners and bloggers made good content as you did the web will be much more useful than ever before
Somebody essentially help to make significantly articles Id state This is the first time I frequented your web page and up to now I surprised with the research you made to make this actual post incredible Fantastic job
I do agree with all the ideas you have introduced on your post They are very convincing and will definitely work Still the posts are very short for newbies May just you please prolong them a little from subsequent time Thank you for the post
you are truly a just right webmaster The site loading speed is incredible It kind of feels that youre doing any distinctive trick In addition The contents are masterwork you have done a great activity in this matter
Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do so Your writing taste has been amazed me Thanks quite nice post
I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again
Just wish to say your article is as surprising The clearness in your post is just cool and i could assume youre an expert on this subject Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post Thanks a million and please keep up the enjoyable work
Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol
I’ve been following your blog for quite some time now, and I’m continually impressed by the quality of your content. Your ability to blend information with entertainment is truly commendable.
fun88 is a reputable online gambling platform that offers a variety of sports events, slot machines, lotteries and other entertainment projects
Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content
Thank you for the auspicious writeup It in fact was a amusement account it Look advanced to more added agreeable from you By the way how could we communicate
I do not even know how I ended up here but I thought this post was great I do not know who you are but certainly youre going to a famous blogger if you are not already Cheers
Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol
Hi i think that i saw you visited my web site thus i came to Return the favore Im attempting to find things to enhance my siteI suppose its ok to use a few of your ideas
Normalmente eu não leio artigos em blogs, mas gostaria de dizer que este artigo me forçou a tentar fazê-lo. Seu estilo de escrita me surpreendeu. Obrigado, ótima postagem
Olá, acho que vi que você visitou meu site, então vim retribuir o favor. Estou tentando encontrar coisas para melhorar meu site. Suponho que não há problema em usar algumas de suas ideias
Obrigado, estou procurando informações sobre esse tópico há algum tempo e a sua é a melhor que descobri até agora. Mas e em relação aos resultados financeiros? Você tem certeza sobre o fornecimento
Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol
Hi Neat post Theres an issue together with your web site in internet explorer may test this IE still is the marketplace chief and a good component of people will pass over your fantastic writing due to this problem
I’ve been following your blog for quite some time now, and I’m continually impressed by the quality of your content. Your ability to blend information with entertainment is truly commendable.