Writing Your First Test with Playwright and TypeScript
Playwright is a modern end-to-end testing framework that supports multiple browsers and is particularly useful for testing web applications. In this guide, we will walk you through the steps to write your first test using Playwright and TypeScript. We will add playwright test to Next.js project of version 14.
Prerequisites
- Basic understanding of TypeScript and web testing concepts.
- Familiarity with npm (Node Package Manager).
Step 1: Installing Node.js
Before you can start using Playwright, you need to have Node.js installed on your machine. You can download it from the official website:
- Visit the Node.js websiteand download the LTS version 18.18 or later.
- Follow the installation instructions for your operating system.
Step 2: Setting Up Your Project
- Create a New Directory:
mkdir playwright-example && cd playwright-example
- Initialize a New Next.js Project:
npx create-next-app@latest
- Choose option for your project, important to choose use `src/` directory:
What is your project named? my-app Would you like to use TypeScript? No / Yes Would you like to use ESLint? No / Yes Would you like to use Tailwind CSS? No / Yes Would you like to use "src/" directory? No / Yes Would you like to use App Router? (recommended) No / Yes Would you like to customize the default import alias (@/*)? No / Yes What import alias would you like configured? @/*
- Install Playwright and TypeScript:Important note: VS code could mark the whole package.json file as red with many errors related to project Id, but everything works correctly anyway. I guess that some kind of bug in compatibility of Next.js and playwright
npm install -D playwright @playwright/test
Step 3: Writing Your First Test
- Create a Test File:Create a new directory called
tests
, and inside it, create a file namedexample.spec.ts
:mkdir -p src/tests && touch src/tests/example.spec.ts
- Write a Simple Test:Here’s an example test that opens a web page and checks the title:
import { test, expect } from '@playwright/test'; test('homepage has Playwright in title', async ({ page }) => { await page.goto('https://playwright.dev'); const title = await page.title(); expect(title).toBe('Fast and reliable end-to-end testing for modern web apps | Playwright'); });
Step 4: Running the Test
- Add a Script to package.json:Update your
package.json
to include a test script:"scripts": { "test": "playwright test" }
- Run the Test:Execute the following command to run your test:
npm test
Step 5: Analyzing the Results
The test output will show whether the test passed or failed. You can troubleshoot any issues based on the error messages provided.
Conclusion
In this guide, we covered the steps to set up and write a simple test using Playwright and TypeScript. Explore more advanced testing scenarios such as interactions, assertions, and different browser contexts.