Building Robust Web Applications with Test-Driven Development and Playwright Maurice de Beijer @mauricedb
© ABL - The Problem Solver 3  Maurice de Beijer  The Problem Solver  Freelance developer/instructor  Twitter: @mauricedb  Web: http://www.theproblemsolver.dev/  E-mail: maurice.de.beijer@gmail.com
What We'll Build Today  Movie Browsing Application  Landing page with navigation  List of top-rated movies  Movie details page  Movie editing functionality  Learning Objectives  TDD workflow in frontend development based on user stories  Writing effective Playwright tests  Building robust web applications  Real-world testing scenarios
© ABL - The Problem Solver 5 Type it out by hand? “Typing it drills it into your brain much better than simply copying and pasting it. You're forming new neuron pathways. Those pathways are going to help you in the future. Help them out now!”
© ABL - The Problem Solver 6 Prerequisites Install Node & NPM Install the GitHub repository
© ABL - The Problem Solver 7 Install Node.js & NPM
© ABL - The Problem Solver 8 Following Along  Repo: https://github.com/mauricedb/tdd-playwright-24  Slides: https://www.theproblemsolver.dev/docs/jsnation-us-2024.pdf
© ABL - The Problem Solver 9 The changes
© ABL - The Problem Solver 10 Clone the GitHub Repository
© ABL - The Problem Solver 11 Install NPM Packages
© ABL - The Problem Solver 12 Start branch  Start with the 00-start branch  git checkout --track origin/00-start
© ABL - The Problem Solver 13 Start the application
Introduction to Test- Driven Development (TDD)
What is Test- Driven Developmen t?  A software development approach where tests are written before the actual code  Tests drive the design and implementation of the code  “Red-Green-Refactor” cycle
The TDD Cycle  Write a failing test (Red)  Write minimal code to make the test pass (Green)  Refactor the code while keeping tests green  Repeat…
Software Testing Pyramid
Benefits of TDD  Improved Code Quality  Fewer bugs and defects  Better code coverage  Cleaner, more maintainable code  Built-in documentation through tests  Faster Development  Catch bugs early in the development cycle  Reduce debugging time  More confident code changes  Easier refactoring  Better Design  Forces modular design  Reduces code coupling  Promotes interface-driven development  Makes code more testable
Common TDD Misconceptio ns  "TDD takes too much time"  Initial investment pays off in reduced debugging and maintenance  Faster identification of issues  Less time spent on manual testing  "I'll write tests later"  Tests written after code tend to be incomplete  Missing edge cases  Code might not be designed for testability  "TDD is only for backend development"  Frontend can benefit greatly from TDD  Ensures consistent UI behavior  Catches regression issues early
Introduction to Playwright A powerful end-to-end testing framework for web applications
What is Playwright?  Modern end-to-end testing framework  Created and maintained as open source by Microsoft  Support for modern browsers  Cross-platform support
Key Features  Auto-wait capabilities  Network interception  Mobile device emulation  Multiple browser contexts  Powerful debugging tools
Why Playwright?  Advantages  Fast and reliable tests  Cross-browser support out of the box  Modern features like web sockets  Rich debugging capabilities  Strong TypeScript support  Use Cases  End-to-end testing  Component testing  Visual regression testing  Performance testing  Network monitoring
Playwright Core Concepts  Browser Contexts  Isolated browser sessions  Independent cookie/storage states  Perfect for testing multi-user scenarios  Auto-waiting  Element availability  Network requests  Animations  No need for explicit waits  Locators  Reliable element selection  Built-in retry logic  Multiple selection strategies
Combining TDD and Playwright  Workflow  Write a failing Playwright test (Red)  Implement the feature  Run tests and fix issues (Green)  Refactor with confidence  Benefits  Consistent UI behavior  Caught regression issues  Documented features  Confident deployments
Installing Playwright
Installing Playwright  Install Playwright from a terminal window in the root folder  npm init playwright@latest  The VS Code extension is a good alternative  Also allows for executing tests
npm init playwright
package.json
Playwright test console mode
© ABL - The Problem Solver 32 Playwright test in UI mode
Implementing the Landing Page
Implementin g Landing Page “As a movie enthusiast I want to see a welcoming landing page So that I can understand what the application offers and navigate to different sections”
© ABL - The Problem Solver 35 Landing Page - Header Section
Best Practices with Playwright  Test user visible behavior  Prefer user-facing attributes to XPath or CSS selectors  page.getByRole() to locate by explicit and implicit accessibility attributes.  page.getByLabel() to locate a form control by associated label's text.  page.getByPlaceholder() to locate an input by placeholder.  page.getByText() to locate by text content.  Use web first assertions  Playwright will wait until the expected condition is met
© ABL - The Problem Solver 37 Landing Page - Header Section with links
Playwright configuratio n  The Playwright configuration can prevent some repeated code  And make it easier to update settings  For example when running against a preview environment in the CI  baseURL: process.env.PLAYWRIGHT_TEST_BASE_URL ?? 'http://localhost:3000’  Group related tests  test.describe()  Use the test hooks that are executed before and after tests  test.beforeEach(), test.afterEach()  test.beforeAll(), test.afterAll()
playwright. config.ts
© ABL - The Problem Solver 40 Landing Page - Main Content
© ABL - The Problem Solver 41 Break time
Implementing the Movie List
Implementin g the Movie List “As a movie enthusiast I want to browse through a list of movies So that I can discover new films and see their ratings”
Playwright test failure  A Playwright doesn’t need to stop at the first failure  Use expect.soft() to keep going after a failed expectation
© ABL - The Problem Solver 45 Movies List - Basic Movie List
Movies List - Grid Layout “As a movie enthusiast I want to see the movies in a responsive grid”
© ABL - The Problem Solver 47 Movies List - Grid Layout
Playwright test size  Favor a few larger tests over many small ones  Break larger tests into steps with test.step()
© ABL - The Problem Solver 49 Movies List - Responsive Grid
Movies List - Sorted by vote “As a movie enthusiast I want to see the movies sorted by vote average in descending order”
© ABL - The Problem Solver 51 Movies List - Sorted by vote
Movies List - Card Component “As a movie enthusiast I want to see each movie in a card with title, poster, rating and description”
Adding test helpers  Use accessibility options to make elements easier to find  Like aria-label and page.getByLabel()  Only use id or data-testid as a last resort  Use data-value to add values in an unformatted format  But only if a value isn’t easy to read from the DOM
© ABL - The Problem Solver 54 Movies List - Card Component
Movies List - 12 Movies per page “As a movie enthusiast I want to see each 12 movie cards at the time”
© ABL - The Problem Solver 56 Movies List - 12 Movies per page
Movies List - Pagination “As a movie enthusiast I want to be able to click a Next button and see more movies”
© ABL - The Problem Solver 58 Movies List - Pagination
Implementing the Navigation Menu
Implementin g the Navigation Menu “As a user of the movie application I want to have a consistent navigation menu So that I can easily access different sections of the application”
© ABL - The Problem Solver 61 Navigation Menu
© ABL - The Problem Solver 62 Navigation Menu
Implementing the Movie Details Page
Implementin g the Movie Details Page “As a movie enthusiast using the application I want to view comprehensive details about a specific movie So that I can make informed decisions about watching it and learn more about the film”
© ABL - The Problem Solver 65 Movie Details - Key Information
Movie Details - Key Information Improved  Requires the The Shawshank Redemption to be the first movie  Might no longer be true in the future  Adapting to the data returned can be more reliable
© ABL - The Problem Solver 67 Movie Details - Key Information Improved
Movie Details - Interaction “As an administrator of the movie application I want to be able to edit a movie in the database So that I can maintain accurate and up-to-date movie details”
© ABL - The Problem Solver 69 Movie Details - Interaction
Implementing the Movie Edit Page
Implementin g the Movie Edit Page “As an administrator of the movie application I want to edit existing movie information in the database So that I can maintain accurate and up-to-date movie details”
© ABL - The Problem Solver 72 Movie Edit - Form Fields
Saving the Movie Edits
Saving the Movie Edits “As an administrator editing movie information I want to save my changes to the movie database So that updated movie information is persisted and immediately available to users”
© ABL - The Problem Solver 75 Movie Edits - Basic Saving
Movie Edits - Improved Saving  Beware: changing data can lead to flaky tests  Reset to the database to a known state before each test  Only make changes to newly added data that doesn’t show up in other tests  Or use Playwright network mocking  Also useful to simulate and test errors like server not available
© ABL - The Problem Solver 77 Movie Edits - Improved Saving
Validating the Movie Edits
Validating the Movie Edits “As an administrator submitting movie changes I want feedback on the validity of my edits So that I can correct any errors before saving to the database”
© ABL - The Problem Solver 80 Movie Edits - Validation
© ABL - The Problem Solver 81 Recommendations with Playwright
Best Practices with Playwright  Test Organization  Group related tests  Use before/after hooks wisely  Share common setup  Test Reliability  Use strong locators  Handle dynamic content  Consider network conditions  Avoid flaky tests but enable retries  Performance  Reuse browser context when possible  Prefer fewer larger tests with soft asserts  Parallel test execution  Minimize unnecessary actions
Best Practices with Playwright  Test user visible behavior  Don’t rely on things a real user doesn’t use like a class name or id  Prefer user-facing attributes to XPath or CSS selectors  page.getByRole() to locate by explicit and implicit accessibility attributes.  page.getByText() to locate by text content.  page.getByLabel() to locate a form control by associated label's text.  page.getByPlaceholder() to locate an input by placeholder.  Use web first assertions  Playwright will wait until the expected condition is met
© ABL - The Problem Solver 84 Thank you for joining Share your thoughts

Building Robust Web Applications with Test-Driven Development and Playwright: A Comprehensive Workshop

  • 2.
    Building Robust Web Applicationswith Test-Driven Development and Playwright Maurice de Beijer @mauricedb
  • 3.
    © ABL -The Problem Solver 3  Maurice de Beijer  The Problem Solver  Freelance developer/instructor  Twitter: @mauricedb  Web: http://www.theproblemsolver.dev/  E-mail: maurice.de.beijer@gmail.com
  • 4.
    What We'll Build Today Movie Browsing Application  Landing page with navigation  List of top-rated movies  Movie details page  Movie editing functionality  Learning Objectives  TDD workflow in frontend development based on user stories  Writing effective Playwright tests  Building robust web applications  Real-world testing scenarios
  • 5.
    © ABL -The Problem Solver 5 Type it out by hand? “Typing it drills it into your brain much better than simply copying and pasting it. You're forming new neuron pathways. Those pathways are going to help you in the future. Help them out now!”
  • 6.
    © ABL -The Problem Solver 6 Prerequisites Install Node & NPM Install the GitHub repository
  • 7.
    © ABL -The Problem Solver 7 Install Node.js & NPM
  • 8.
    © ABL -The Problem Solver 8 Following Along  Repo: https://github.com/mauricedb/tdd-playwright-24  Slides: https://www.theproblemsolver.dev/docs/jsnation-us-2024.pdf
  • 9.
    © ABL -The Problem Solver 9 The changes
  • 10.
    © ABL -The Problem Solver 10 Clone the GitHub Repository
  • 11.
    © ABL -The Problem Solver 11 Install NPM Packages
  • 12.
    © ABL -The Problem Solver 12 Start branch  Start with the 00-start branch  git checkout --track origin/00-start
  • 13.
    © ABL -The Problem Solver 13 Start the application
  • 14.
  • 15.
    What is Test- Driven Developmen t? A software development approach where tests are written before the actual code  Tests drive the design and implementation of the code  “Red-Green-Refactor” cycle
  • 16.
    The TDD Cycle  Writea failing test (Red)  Write minimal code to make the test pass (Green)  Refactor the code while keeping tests green  Repeat…
  • 17.
  • 18.
    Benefits of TDD  ImprovedCode Quality  Fewer bugs and defects  Better code coverage  Cleaner, more maintainable code  Built-in documentation through tests  Faster Development  Catch bugs early in the development cycle  Reduce debugging time  More confident code changes  Easier refactoring  Better Design  Forces modular design  Reduces code coupling  Promotes interface-driven development  Makes code more testable
  • 19.
    Common TDD Misconceptio ns  "TDD takestoo much time"  Initial investment pays off in reduced debugging and maintenance  Faster identification of issues  Less time spent on manual testing  "I'll write tests later"  Tests written after code tend to be incomplete  Missing edge cases  Code might not be designed for testability  "TDD is only for backend development"  Frontend can benefit greatly from TDD  Ensures consistent UI behavior  Catches regression issues early
  • 20.
    Introduction to Playwright A powerfulend-to-end testing framework for web applications
  • 21.
    What is Playwright?  Modernend-to-end testing framework  Created and maintained as open source by Microsoft  Support for modern browsers  Cross-platform support
  • 22.
    Key Features  Auto-waitcapabilities  Network interception  Mobile device emulation  Multiple browser contexts  Powerful debugging tools
  • 23.
    Why Playwright?  Advantages  Fastand reliable tests  Cross-browser support out of the box  Modern features like web sockets  Rich debugging capabilities  Strong TypeScript support  Use Cases  End-to-end testing  Component testing  Visual regression testing  Performance testing  Network monitoring
  • 24.
    Playwright Core Concepts  Browser Contexts Isolated browser sessions  Independent cookie/storage states  Perfect for testing multi-user scenarios  Auto-waiting  Element availability  Network requests  Animations  No need for explicit waits  Locators  Reliable element selection  Built-in retry logic  Multiple selection strategies
  • 25.
    Combining TDD and Playwright  Workflow Write a failing Playwright test (Red)  Implement the feature  Run tests and fix issues (Green)  Refactor with confidence  Benefits  Consistent UI behavior  Caught regression issues  Documented features  Confident deployments
  • 26.
  • 27.
    Installing Playwright  Install Playwrightfrom a terminal window in the root folder  npm init playwright@latest  The VS Code extension is a good alternative  Also allows for executing tests
  • 28.
  • 29.
  • 30.
  • 31.
    © ABL -The Problem Solver 32 Playwright test in UI mode
  • 32.
  • 33.
    Implementin g Landing Page “As amovie enthusiast I want to see a welcoming landing page So that I can understand what the application offers and navigate to different sections”
  • 34.
    © ABL -The Problem Solver 35 Landing Page - Header Section
  • 35.
    Best Practices with Playwright  Test uservisible behavior  Prefer user-facing attributes to XPath or CSS selectors  page.getByRole() to locate by explicit and implicit accessibility attributes.  page.getByLabel() to locate a form control by associated label's text.  page.getByPlaceholder() to locate an input by placeholder.  page.getByText() to locate by text content.  Use web first assertions  Playwright will wait until the expected condition is met
  • 36.
    © ABL -The Problem Solver 37 Landing Page - Header Section with links
  • 37.
    Playwright configuratio n  The Playwrightconfiguration can prevent some repeated code  And make it easier to update settings  For example when running against a preview environment in the CI  baseURL: process.env.PLAYWRIGHT_TEST_BASE_URL ?? 'http://localhost:3000’  Group related tests  test.describe()  Use the test hooks that are executed before and after tests  test.beforeEach(), test.afterEach()  test.beforeAll(), test.afterAll()
  • 38.
  • 39.
    © ABL -The Problem Solver 40 Landing Page - Main Content
  • 40.
    © ABL -The Problem Solver 41 Break time
  • 41.
  • 42.
    Implementin g the Movie List “Asa movie enthusiast I want to browse through a list of movies So that I can discover new films and see their ratings”
  • 43.
    Playwright test failure  APlaywright doesn’t need to stop at the first failure  Use expect.soft() to keep going after a failed expectation
  • 44.
    © ABL -The Problem Solver 45 Movies List - Basic Movie List
  • 45.
    Movies List - GridLayout “As a movie enthusiast I want to see the movies in a responsive grid”
  • 46.
    © ABL -The Problem Solver 47 Movies List - Grid Layout
  • 47.
    Playwright test size  Favora few larger tests over many small ones  Break larger tests into steps with test.step()
  • 48.
    © ABL -The Problem Solver 49 Movies List - Responsive Grid
  • 49.
    Movies List - Sortedby vote “As a movie enthusiast I want to see the movies sorted by vote average in descending order”
  • 50.
    © ABL -The Problem Solver 51 Movies List - Sorted by vote
  • 51.
    Movies List - Card Component “Asa movie enthusiast I want to see each movie in a card with title, poster, rating and description”
  • 52.
    Adding test helpers  Useaccessibility options to make elements easier to find  Like aria-label and page.getByLabel()  Only use id or data-testid as a last resort  Use data-value to add values in an unformatted format  But only if a value isn’t easy to read from the DOM
  • 53.
    © ABL -The Problem Solver 54 Movies List - Card Component
  • 54.
    Movies List - 12Movies per page “As a movie enthusiast I want to see each 12 movie cards at the time”
  • 55.
    © ABL -The Problem Solver 56 Movies List - 12 Movies per page
  • 56.
    Movies List - Pagination “Asa movie enthusiast I want to be able to click a Next button and see more movies”
  • 57.
    © ABL -The Problem Solver 58 Movies List - Pagination
  • 58.
  • 59.
    Implementin g the Navigation Menu “As auser of the movie application I want to have a consistent navigation menu So that I can easily access different sections of the application”
  • 60.
    © ABL -The Problem Solver 61 Navigation Menu
  • 61.
    © ABL -The Problem Solver 62 Navigation Menu
  • 62.
  • 63.
    Implementin g the Movie DetailsPage “As a movie enthusiast using the application I want to view comprehensive details about a specific movie So that I can make informed decisions about watching it and learn more about the film”
  • 64.
    © ABL -The Problem Solver 65 Movie Details - Key Information
  • 65.
    Movie Details - Key Information Improved Requires the The Shawshank Redemption to be the first movie  Might no longer be true in the future  Adapting to the data returned can be more reliable
  • 66.
    © ABL -The Problem Solver 67 Movie Details - Key Information Improved
  • 67.
    Movie Details - Interaction “As anadministrator of the movie application I want to be able to edit a movie in the database So that I can maintain accurate and up-to-date movie details”
  • 68.
    © ABL -The Problem Solver 69 Movie Details - Interaction
  • 69.
  • 70.
    Implementin g the Movie EditPage “As an administrator of the movie application I want to edit existing movie information in the database So that I can maintain accurate and up-to-date movie details”
  • 71.
    © ABL -The Problem Solver 72 Movie Edit - Form Fields
  • 72.
  • 73.
    Saving the Movie Edits “Asan administrator editing movie information I want to save my changes to the movie database So that updated movie information is persisted and immediately available to users”
  • 74.
    © ABL -The Problem Solver 75 Movie Edits - Basic Saving
  • 75.
    Movie Edits - Improved Saving Beware: changing data can lead to flaky tests  Reset to the database to a known state before each test  Only make changes to newly added data that doesn’t show up in other tests  Or use Playwright network mocking  Also useful to simulate and test errors like server not available
  • 76.
    © ABL -The Problem Solver 77 Movie Edits - Improved Saving
  • 77.
  • 78.
    Validating the Movie Edits “As anadministrator submitting movie changes I want feedback on the validity of my edits So that I can correct any errors before saving to the database”
  • 79.
    © ABL -The Problem Solver 80 Movie Edits - Validation
  • 80.
    © ABL -The Problem Solver 81 Recommendations with Playwright
  • 81.
    Best Practices with Playwright  Test Organization Group related tests  Use before/after hooks wisely  Share common setup  Test Reliability  Use strong locators  Handle dynamic content  Consider network conditions  Avoid flaky tests but enable retries  Performance  Reuse browser context when possible  Prefer fewer larger tests with soft asserts  Parallel test execution  Minimize unnecessary actions
  • 82.
    Best Practices with Playwright  Test uservisible behavior  Don’t rely on things a real user doesn’t use like a class name or id  Prefer user-facing attributes to XPath or CSS selectors  page.getByRole() to locate by explicit and implicit accessibility attributes.  page.getByText() to locate by text content.  page.getByLabel() to locate a form control by associated label's text.  page.getByPlaceholder() to locate an input by placeholder.  Use web first assertions  Playwright will wait until the expected condition is met
  • 83.
    © ABL -The Problem Solver 84 Thank you for joining Share your thoughts

Editor's Notes

  • #8 https://bit.ly/487wSyx