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

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:

Step 2: Setting Up Your Project

  1. Create a New Directory:
    mkdir playwright-example && cd playwright-example
  2. Initialize a New Next.js Project:
    npx create-next-app@latest
  3. 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? @/*
  4. Install Playwright and TypeScript:
    npm install -D playwright @playwright/test
    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

Step 3: Writing Your First Test

  1. Create a Test File:Create a new directory called tests, and inside it, create a file named example.spec.ts:
    mkdir -p src/tests && touch src/tests/example.spec.ts
  2. 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

  1. Add a Script to package.json:Update your package.json to include a test script:
    "scripts": {
     "test": "playwright test"
    }
  2. 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.

Additional Resources