How to Test File Type, Size and Upload Errors in Playwright: Complete Practical Guide


 Have you ever uploaded a PDF to a website and received an error saying that the file format is not supported?

Or tried uploading a large document and received a message saying that the maximum file size has been exceeded?

These are examples of file upload validation.

Web applications need rules to decide which files users can upload, how large those files can be, and what should happen when an upload fails.

For automation testers, checking these rules is an important part of functional testing.

Playwright can automate file type validation, file size validation, and upload error testing using TypeScript.

In this guide, you will learn how to test valid and invalid file formats, create files of different sizes, verify error messages, and automate realistic file upload scenarios.

The examples use Playwright with TypeScript and explain each step in simple language.

What Is File Type and Size Validation?

File type validation checks whether an uploaded document belongs to an allowed format.

File size validation checks whether the document is within the maximum size permitted by the application.

For example, imagine a job application website with these requirements:

  • Allowed formats: PDF and DOCX.

  • Maximum file size: 5 MB.

  • Empty documents are not accepted.

  • Unsupported documents must display an error.

A tester should verify that the application follows every requirement.

Validation

Example

Expected Result

Valid file type

resume.pdf

Accepted

Invalid file type

resume.exe

Rejected

Valid file size

2 MB

Accepted

Invalid file size

8 MB

Rejected

Empty file

0 KB

Rejected if prohibited

Missing attachment

No file selected

Required-field error

The exact rules depend on the application.

Why Should Testers Validate File Types?

Imagine a website that allows users to upload profile pictures.

The application should accept supported image formats such as JPEG and PNG.

Now imagine someone uploads an unrelated document instead.

The application should not process it as a valid image.

File type validation helps applications handle expected documents and reject unsupported formats.

Common file types include:

File Format

Extension

Common Usage

PDF

.pdf

Reports and resumes

JPEG

.jpg, .jpeg

Photographs

PNG

.png

Images and screenshots

DOCX

.docx

Word documents

CSV

.csv

Spreadsheet data

TXT

.txt

Text documents

XLSX

.xlsx

Excel spreadsheets

A website should clearly communicate which formats it accepts.

How to Test Allowed File Types in Playwright

Start by understanding the application's requirements.

For example, assume a resume upload page accepts only PDF and DOCX files.

Create the following test files:

tests/files/

  resume.pdf

  resume.docx

  image.png

  notes.txt

Use valid sample documents when the application actually processes their contents.

Test 1: Upload a valid PDF

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


test('should accept a PDF resume', async ({ page }) => {


  await page.goto('https://example.com/resume');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/resume.pdf');


  await page.getByRole('button', {

    name: 'Upload Resume'

  }).click();


  await expect(

    page.getByText('File uploaded successfully')

  ).toBeVisible();


});

This test assumes that the application displays the specified success message after accepting the document.

Test 2: Upload a valid DOCX file

test('should accept a DOCX resume', async ({ page }) => {


  await page.goto('https://example.com/resume');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/resume.docx');


  await page.getByRole('button', {

    name: 'Upload Resume'

  }).click();


  await expect(

    page.getByText('File uploaded successfully')

  ).toBeVisible();


});

These tests verify that the application accepts the required document formats.

How to Test Invalid File Types in Playwright

Negative file type testing checks whether the application rejects unsupported documents.

For example, if the application accepts only PDF and DOCX files, a PNG image should not be accepted as a resume.

Example:

test('should reject an unsupported file type', async ({ page }) => {


  await page.goto('https://example.com/resume');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/image.png');


  await page.getByRole('button', {

    name: 'Upload Resume'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Unsupported file format');


});

The expected error message must match the actual application's requirements.

This test verifies more than the browser's file selection. It checks whether the application rejects the unsupported document after the upload action.

What Is the HTML Accept Attribute?

The HTML accept attribute tells the browser which file types should be displayed in the file selection window.

Example:

<input

  type="file"

  accept=".pdf,.docx"

>

This indicates that PDF and DOCX files are expected.

You can inspect this attribute using Playwright.

const fileInput = page.locator(

  'input[type="file"]'

);


await expect(fileInput).toHaveAttribute(

  'accept',

  '.pdf,.docx'

);

However, there is something important to understand.

The accept attribute is not a security mechanism.

It guides the browser's file selection interface, but it does not guarantee that unsupported files cannot reach the server.

A user or automated test may still provide a file directly.

The backend must independently validate uploaded files.

Why File Extensions Alone Are Not Enough

Consider two files:

  1. document.pdf containing a valid PDF.

  2. document.pdf containing ordinary text.

Both files have the same extension.

However, their actual contents are different.

This is why reliable applications should not trust only the filename.

File validation may involve checking:

  • Filename extension.

  • MIME type.

  • Actual file signature or content.

  • Document structure.

  • Application-specific business rules.

For security-sensitive applications, server-side validation is especially important.

How to Test a Misleading File Extension

Playwright can create an in-memory file payload.

test('should reject incorrect file content', async ({ page }) => {


  await page.goto('https://example.com/resume');


  await page.locator('input[type="file"]')

    .setInputFiles({

      name: 'fake-resume.pdf',

      mimeType: 'application/pdf',

      buffer: Buffer.from('This is not a real PDF')

    });


  await page.getByRole('button', {

    name: 'Upload Resume'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Invalid document');


});

This test checks whether the application validates actual document content rather than trusting only the filename and declared MIME type.

The exact validation behavior depends on the application's backend.

What Is File Size Validation?

File size validation checks whether a document is within the maximum size allowed by an application.

For example:

A college application website may allow students to upload certificates up to 2 MB.

If a student uploads a 10 MB document, the website should reject it and display a helpful message.

Common file size restrictions include:

  • Maximum 1 MB.

  • Maximum 2 MB.

  • Maximum 5 MB.

  • Maximum 10 MB.

  • Maximum 25 MB.

These are examples, not universal limits.

Always use the actual application requirement.

How to Create Files of Different Sizes for Testing

To test file size restrictions, you need files with known sizes.

Node.js provides the Buffer API, which can generate file content.

Example:

import fs from 'node:fs';


const fileContent = Buffer.alloc(

  6 * 1024 * 1024,

  'A'

);


fs.writeFileSync(

  'tests/files/large-file.txt',

  fileContent

);

This creates a file containing 6 MiB of data.

Remember the difference:

  • 1 MB commonly means 1,000,000 bytes.

  • 1 MiB means 1,048,576 bytes.

Your test should follow the unit and limit used in the application requirements.

How to Test Files Below the Maximum Size

Assume the application allows files up to 5 MB.

A 2 MB file should be accepted.

Example:

test('should accept a file below the size limit', async ({ page }) => {


  await page.goto('https://example.com/upload');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/2mb-file.pdf');


  await page.getByRole('button', {

    name: 'Upload'

  }).click();


  await expect(

    page.getByText('Upload successful')

  ).toBeVisible();


});

This checks the application's behavior for a file below the maximum limit.

How to Test Files Above the Maximum Size

Now upload a file larger than 5 MB.

Example:

test('should reject a file above the size limit', async ({ page }) => {


  await page.goto('https://example.com/upload');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/6mb-file.pdf');


  await page.getByRole('button', {

    name: 'Upload'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Maximum file size is 5 MB');


});

The expected behavior is that the application rejects the oversized document and explains the problem.

Also verify that the invalid document is not marked as successfully uploaded.

How to Test the Exact Maximum File Size

Boundary testing is extremely important.

Suppose the maximum permitted file size is 5 MB.

You should not test only a 2 MB file and a 10 MB file.

You should also test files around the exact limit.

For example:

Test File

Expected Result

4.9 MB

Accept

5 MB

Accept if the limit is inclusive

5.1 MB

Reject

The exact result depends on whether the requirement defines the limit as inclusive or exclusive.

This is called boundary value testing.

It helps identify problems that ordinary positive and negative tests may miss.

Example: Verify the actual file size

import fs from 'node:fs/promises';


const stats = await fs.stat(

  'tests/files/large-file.pdf'

);


const sizeInBytes = stats.size;


console.log('File size:', sizeInBytes);

You can use this information to verify that your test fixtures are actually within the expected size ranges.

How to Test Empty File Uploads

An empty file contains zero bytes.

Some applications allow empty files, while others reject them.

For example, a resume portal should normally reject an empty resume because it contains no useful information.

Create an empty test file:

import fs from 'node:fs';


fs.writeFileSync(

  'tests/files/empty.txt',

  ''

);

Now automate the upload:

test('should reject an empty document', async ({ page }) => {


  await page.goto('https://example.com/upload');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/empty.txt');


  await page.getByRole('button', {

    name: 'Upload'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Empty files are not allowed');


});

This verifies whether the application handles zero-byte documents according to its requirements.

How to Test Upload Error Messages in Playwright

Displaying an error is not enough.

The error should explain the problem clearly and help users understand what they need to do.

For example:

Situation

Expected Error

Unsupported format

Please upload a PDF or DOCX file

Oversized document

File size must be below 5 MB

Empty document

Empty files are not allowed

Missing attachment

Please select a file

Corrupted document

The uploaded document could not be processed

Network interruption

Upload failed. Please try again

You can verify error messages using Playwright assertions.

Example:

await expect(

  page.getByRole('alert')

).toHaveText('File size must be below 5 MB');

For applications that display an error message next to the upload field, locate that specific message instead.

What Should a Good Upload Error Message Contain?

A helpful error should explain:

  1. What went wrong.

  2. Why the file was rejected.

  3. What the user should do next.

For example:

Instead of:

Invalid file

A better message is:

Please upload a PDF document smaller than 5 MB.

Automation testers should verify that the application displays the expected and useful message.

How to Test Upload Errors Caused by Network Problems

File upload problems do not always happen because of an incorrect document.

Sometimes the network connection fails while the file is being transferred.

For example:

A student uploads a certificate, but the internet connection is interrupted before the server receives the complete document.

The application should handle this failure without showing a false success message.

You can simulate a failed upload response using Playwright request routing when the application uses a known upload endpoint.

Example:

test('should display an error when upload fails', async ({ page }) => {


  await page.route('**/api/upload', async route => {


    await route.fulfill({

      status: 500,

      contentType: 'application/json',

      body: JSON.stringify({

        message: 'Upload failed'

      })

    });


  });


  await page.goto('https://example.com/upload');


  await page.locator('input[type="file"]')

    .setInputFiles('tests/files/resume.pdf');


  await page.getByRole('button', {

    name: 'Upload'

  }).click();


  await expect(

    page.getByRole('alert')

  ).toContainText('Upload failed');


});

The route pattern and expected response must match the actual application's API contract.

This test simulates a server failure. It is not the same as physically disconnecting the user's internet connection.

How to Build a File Validation Test Matrix

A test matrix helps testers cover important scenarios without missing requirements.

Here is an example for a resume upload application.

Test ID

Scenario

Test Data

Expected Result

FT01

Valid PDF

resume.pdf

Accepted

FT02

Valid DOCX

resume.docx

Accepted

FT03

Invalid PNG

image.png

Rejected

FT04

Invalid TXT

notes.txt

Rejected

FS01

Below size limit

2 MB PDF

Accepted

FS02

Exact size limit

5 MB PDF

Accepted if inclusive

FS03

Above size limit

6 MB PDF

Rejected

FS04

Empty document

0-byte file

Rejected if prohibited

FE01

Missing attachment

No file

Required error

FE02

Corrupted PDF

Invalid PDF content

Rejected

FE03

Server failure

Valid PDF + simulated error

Failure message

This matrix can become the foundation of your automation suite.

Common Mistakes in File Type and Size Testing

Mistake 1: Testing only file extensions

A filename ending in .pdf does not prove that the document contains valid PDF data.

Better approach: Include tests for actual document content and server-side validation.

Mistake 2: Testing only very small and very large files

This misses errors around the exact file size limit.

Better approach: Use boundary value testing.

Mistake 3: Checking only whether an error appears

An application might display an error but still store the invalid document.

Better approach: Verify that the document was actually rejected.

Mistake 4: Using the wrong size unit

MB and MiB are not exactly the same.

Better approach: Calculate test file sizes in bytes and follow the application's specification.

Mistake 5: Ignoring server-side validation

Browser-side validation can be bypassed.

Better approach: Verify the backend response and the final application state.

Best Practices for File Validation Automation

  • Read the file upload requirements before writing tests.

  • Maintain valid and invalid test documents separately.

  • Test every supported file format.

  • Include files with misleading extensions.

  • Test files below, at, and above the size limit.

  • Verify error messages.

  • Check that rejected documents are not stored.

  • Use API mocking for controlled server failures.

  • Avoid real customer documents.

  • Run tests in CI/CD.

  • Keep test fixtures reusable and easy to maintain.

Frequently Asked Questions About File Type, Size and Upload Errors

1. How do I test file type validation in Playwright?

Upload both supported and unsupported file formats using setInputFiles(). Then verify whether the application accepts or rejects each document.

2. How do I test maximum file size in Playwright?

Create files with known sizes, upload them, and verify the application's behavior below, at, and above the configured size limit.

3. Can Playwright create large files for testing?

Yes. Node.js Buffer and file system APIs can generate files of specific sizes during test preparation.

4. How do I test invalid file extensions?

Upload a file with an unsupported extension and verify that the application displays the expected validation error.

5. Can Playwright test MIME type validation?

Yes. You can provide a file payload with a specified MIME type. To verify actual file validation, also test the file content and backend behavior.

6. What happens if the file extension is correct but the content is wrong?

A properly designed application should reject files that do not contain the expected document format. Test this using files with misleading extensions.

7. How do I test empty file uploads?

Create a zero-byte file using Node.js and upload it. Verify whether the application accepts or rejects it according to the requirements.

8. How do I test upload error messages?

Use Playwright assertions such as toHaveText() or toContainText() to verify the expected message.

9. Is the HTML accept attribute enough for file validation?

No. It guides file selection but does not provide complete security. Server-side validation is necessary.

10. Why is boundary value testing important for file uploads?

It identifies problems around the maximum allowed file size. Testing values immediately below, at, and above the limit helps verify the application's exact behavior.

Conclusion

File type, file size, and upload error validation are essential parts of web application testing.

Playwright allows testers to automate these scenarios using file inputs, generated test files, assertions, and network routing.

However, reliable validation requires more than checking the filename or extension.

Test the actual document content, verify size restrictions, check meaningful error messages, and confirm that rejected files are not processed or stored.

By combining positive testing, negative testing, and boundary value testing, you can build a more dependable file upload automation framework.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide