Guide to Setting Up Playwright E2E Testing in NextJS
Introduction
- Playwright is a powerful automated testing framework developed by Microsoft, allowing for End-to-End (E2E) testing across modern browsers such as Chromium, Firefox, and WebKit.
- Key advantages include fast execution speed due to its event-driven architecture, auto-wait capabilities that reduce "flaky" errors, default support for parallel execution, and the Codegen tool which helps generate automated test scripts by recording user interactions.
Prerequisites
This article is a continuation of my previous posts, so I will not provide the test code files again; please review them to have the source code ready before proceeding.
Detail
First, if your project does not have Playwright yet, you can set it up quickly as follows; this command will install the necessary packages and create a config file along with demo test files:
Or install the following packages manually:
Update playwright.config.ts file:
The code above configures the test environment for Playwright: defining the directory containing test files as ./e2e, filtering files by the .test.ts format, setting the baseURL to optimize navigation commands, and configuring the webServer so that Playwright automatically starts the Next.js application at port 3000 before starting the testing process.
Create e2e/ChatBot.e2e.test.ts file:
- This code executes a test scenario for the ChatBot workflow: accessing the chatbot page, finding the input field via testId to fill in a question and pressing Enter, then using expect functions to verify the visibility of the user's message, the loading indicator, and finally confirming that the AI's response content has appeared on the interface.
- Note that the filename must follow the definition in playwright.config.ts, which is placed in the "e2e" folder and ends with ".test.ts" to run correctly.
Update package.json file to add test execution scripts:
These scripts help optimize the workflow:
- test:e2e is used to execute all written tests.
- pw:gen activates the automated code generation tool, allowing you to perform actions directly on the browser while Playwright automatically records them into the specified test source file; you can change the filename as needed.
- Please attention that you need to start server before to run e2e test.
When using playwright codegen, a browser will open and the code content will be generated corresponding to each of your actions.
The test execution results are as follows:
You can also view the report as follows:
Happy coding!
Comments
Post a Comment