Horje
Next.js Playwright Testing

Playwright is a testing framework that allows us to run End-to-End (E2E) tests. It allows automated browser interactions in headless mode, enabling comprehensive testing of user interfaces, navigation, and functionality, ensuring robust and reliable web applications. Testing becomes even more essential for NextJS projects as it involves server-side and client-side rendering.

This article will guide you through setting up and writing Playwright tests in your NextJS application.

Prerequisites:

Steps to Test a NextJS App with Playwright

Step 1: Create a NextJS Application using the following command.

npx create-next-app@latest

Step 2: Install Playwright using the following command.

npm init playwright@latest

You will be prompted with the following questions to choose how you would like to set up Playwright:

✔ Do you want to use TypeScript or JavaScript? · JavaScript 
✔ Where to put your end-to-end tests? · tests/e2e
✔ Add a GitHub Actions workflow? (y/N) · false
✔ Install Playwright browsers (can be done manually via 'npx playwright install')? (Y/n) · true

Note: We can also use the below command for automatic project setup along with playwright

 npx create-next-app@latest --example with-playwright with-playwright-app

Project Structure:

Screenshot-2024-07-05-212517

Project Structure

After that, Playwright will install the necessary dependencies and create a playwright.config file in your NextJS project and the updated dependencies in package.json file will look like this.

"dependencies": {
"next": "14.2.4",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@playwright/test": "^1.45.1",
}

Step 3: Add the following script configuration to your package.json.

"scripts": {    
"test:e2e": "playwright test"
}

Step 4: Now you can try running the default playwright test examples by running this command in your terminal.

npx playwright test
playwright-test

Default Playwright tests running successfully

We can even see the HTML Test Reports of default playwright tests by running this command:

npx playwright show-report

Step 5: Remove default Playwright Tests and Create a new test file in your NextJS project.
Once you have finished exploring the default Playwright tests, you can remove initial test files.

Here’s how you can do it:

del tests\e2e\example.spec.js
Remove-Item -Path "tests-examples" -Recurse -Force

Now, Let us create a new test file in tests/e2e folder:

New-Item -Path "tests\e2e\index.specs.js" -ItemType "file"

Example: Let’s create a simple example, where we have a Counter component in the app/page.js file in a NextJS project, and then test it with Playwright.

JavaScript
// app/page.js

"use client";

import React, { useState } from 'react';

export default function Counter() {
    const [count, setCount] = useState(0);

    const increment = () => {
        setCount(prevCount => prevCount + 1);
    };

    const decrement = () => {
        setCount(prevCount => prevCount - 1);
    };

    return (
        <main>
            <h1> Counter: {count} </h1>
            <div className='mt-10'>
                <button onClick={increment}>
                    Increment
                </button>
                <button onClick={decrement}>
                    Decrement
                </button>
            </div>
        </main>
    );
}
JavaScript
// tests/e2e/index.spec.js

import { test, expect } from '@playwright/test'

test('Counter component test', async ({ page }) => {
    // Navigate to the Next.js application URL
    await page.goto('http://localhost:3000')

    // Initial count should be 0
    const initialCount = await page.textContent('h1')
    expect(initialCount).toBe('Counter: 0')

    // Increment the counter
    await page.click('button:text("Increment")')
    await page.waitForTimeout(500) // Wait for state update

    // After incrementing, count should be 1
    const incrementedCount = await page.textContent('h1')
    expect(incrementedCount).toBe('Counter: 1')

    // Decrement the counter
    await page.click('button:text("Decrement")')
    await page.waitForTimeout(500) // Wait for state update

    // After decrementing, count should be 0 again
    const decrementedCount = await page.textContent('h1')
    expect(decrementedCount).toBe('Counter: 0')
})

Step 6: Run your application test cases and view the HTML Test Reports using the following commands.

Start your Next.js development server:

npm run dev

In a separate terminal, run your Playwright tests:

npm run test:e2e

Output:

The terminal will display the test execution process, showing which tests are running and their pass/fail status. It should look something like this:

Screenshot-2024-07-05-202853

Playwright test passed successfully

Now, To view the HTML Test Reports, run this command in your terminal:

npx playwright show-report
Screenshot-2024-07-05-203238



Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How To Fix The Error “window is not defined” in Next.Js? How To Fix The Error “window is not defined” in Next.Js?
How To Convert From .ejs Template to React? How To Convert From .ejs Template to React?
generateImageMetadata Next.js generateImageMetadata Next.js
NextJS 14 - Latest Updates and Features NextJS 14 - Latest Updates and Features
Caching in Next.js Caching in Next.js

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18