How to Test Sorting and Pagination Together Using Playwright: Complete Guide



Imagine that you are using an e-commerce website containing 200 mobile phones.

You want to find the cheapest mobile phone.

You select the Price: Low to High option.

The website sorts the products based on price.

However, the website displays only 10 products on each page.

You click Next to view more products.

Now an important question appears:

Are the products still sorted correctly on the second page?

This is where sorting and pagination testing becomes important.

Sorting and pagination are two common features used in modern web applications.

Sorting arranges records in a particular order, while pagination divides those records into smaller pages.

Both features may work correctly when tested separately but still fail when used together.

For example:

  • The first page is sorted, but the second page is not.

  • Changing the sorting order displays duplicate records.

  • Clicking Next resets the sorting order.

  • The same product appears on multiple pages.

  • Records disappear after changing the sort option.

  • The application displays an incorrect total count.

Testing sorting and pagination together in Playwright means verifying that records remain correctly ordered, complete and consistent while users change sorting options and navigate between pages.

In this guide, you will learn how to test both features using Playwright and TypeScript with practical examples.

What Is Sorting in Web Applications?

Sorting is the process of arranging records based on a selected field.

For example, an e-commerce application may display products based on:

  • Product name.

  • Price.

  • Rating.

  • Date added.

  • Popularity.

There are two common sorting directions.

1. Ascending Order

Ascending order arranges values from smaller to larger.

Examples:

Price: Low to High

₹500 → ₹1,000 → ₹2,000 → ₹5,000

Names:

Apple → Banana → Mango → Orange

2. Descending Order

Descending order arranges values from larger to smaller.

Examples:

Price: High to Low

₹5,000 → ₹2,000 → ₹1,000 → ₹500

Names:

Orange → Mango → Banana → Apple

What Is Pagination?

Pagination divides a large list of records into smaller pages.

For example:

A website contains 100 products and displays 10 products per page.

  • Page 1: Products 1–10.

  • Page 2: Products 11–20.

  • Page 3: Products 21–30.

  • Page 10: Products 91–100.

Users can navigate through these pages using page numbers, Next and Previous buttons.

Why Should You Test Sorting and Pagination Together?

Testing sorting and pagination separately does not guarantee that both features work correctly together.

Consider this example:

A product application contains 50 products.

You select Price: Low to High.

The application sorts all 50 products and displays the first 10.

When you click Next, the second page should contain the next 10 products in the same sorted order.

If the application sorts only the current page instead of the complete result set, users may see incorrect results.

This can create serious problems.

Important reasons for combined testing

1. Maintain correct sorting across pages

The selected sorting order should remain consistent when moving between pages.

2. Prevent duplicate records

The same product should not appear on multiple pages unexpectedly.

3. Prevent missing records

Every eligible record should appear in the complete result set.

4. Verify sorting direction

Ascending and descending order should work correctly across the entire dataset.

5. Validate user experience

Users expect sorting to remain active while they explore additional records.

6. Detect backend and frontend integration issues

The frontend and backend must apply sorting and pagination consistently.

What Should You Test in Sorting and Pagination?

Use this checklist before developing your automation scripts.

Test scenario

Expected result

Sort price ascending

Products appear from lowest to highest

Sort price descending

Products appear from highest to lowest

Sort by name

Products follow the selected alphabetical order

Click Next after sorting

Sorting remains active

Click Previous after sorting

Previous records remain correctly sorted

Change sorting on page 3

Application follows its defined page-reset or retention behaviour

Navigate to last page

Final records follow the selected order

Sort records with equal values

Records follow a defined tie-breaking rule

Refresh the page

Sorting state follows the application's design

Apply sorting to an empty result

Correct empty state appears

An important business rule is that sorting should generally be applied to the complete filtered dataset before pagination.

The application may also reset the current page to page 1 whenever a new sorting option is selected. This is common because the first page should display the highest-priority records in the newly selected order.

However, the expected behaviour must be confirmed with the application's product requirements.

How to Test Sorting and Pagination Together Using Playwright

Let's use an online shopping application as our example.

Assume that the application contains these products:

Product

Price

Headphones

₹2,000

Keyboard

₹1,000

Monitor

₹8,000

Mouse

₹500

Laptop

₹50,000

Webcam

₹1,500

The application displays two products per page.

Our objective is to test price sorting and pagination.

Step 1: Create the Playwright Test File

Create a file:

sorting-pagination.spec.ts

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


test('Verify product sorting and pagination', async ({ page }) => {


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


  await expect(

    page.getByRole('heading', { name: 'Products' })

  ).toBeVisible();


});

This test opens the product page and verifies that the page heading is visible.

Replace the sample URL with your actual application URL.

Step 2: Test Price Sorting in Ascending Order

First, select Price: Low to High.

test('Verify price sorting ascending', async ({ page }) => {


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


  await page.getByLabel('Sort by').selectOption('price-asc');


  const prices = await page

    .locator('[data-testid="product-price"]')

    .allTextContents();


  const numericPrices = prices.map(price =>

    Number(price.replace(/[^\d.]/g, ''))

  );


  expect(numericPrices).toEqual(

    [...numericPrices].sort((a, b) => a - b)

  );


});

Explanation:

  • getByLabel() locates the sorting dropdown.

  • selectOption() selects ascending price order.

  • allTextContents() collects the displayed prices.

  • map() converts the displayed price strings into numbers.

  • sort() creates the expected ascending order.

  • toEqual() compares the actual and expected arrays.

This verifies that the displayed products are arranged from lowest to highest price.

The example assumes that prices are represented in a simple numeric format. Applications with multiple currencies, decimal formats or localized number formatting may need a dedicated price parser.

Step 3: Test Price Sorting in Descending Order

Now test Price: High to Low.

test('Verify price sorting descending', async ({ page }) => {


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


  await page.getByLabel('Sort by').selectOption('price-desc');


  const prices = await page

    .locator('[data-testid="product-price"]')

    .allTextContents();


  const numericPrices = prices.map(price =>

    Number(price.replace(/[^\d.]/g, ''))

  );


  expect(numericPrices).toEqual(

    [...numericPrices].sort((a, b) => b - a)

  );


});

This verifies that the displayed prices follow descending order.

Step 4: Verify Sorting After Clicking Next

This is the most important combined scenario.

Assume that the application displays two products per page.

When users select ascending sorting, the first page should contain the two lowest-priced products.

The second page should contain the next two lowest-priced products.

Let's automate this behaviour.

test('Verify sorting is maintained on next page', async ({ page }) => {


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


  await page.getByLabel('Sort by').selectOption('price-asc');


  const getPrices = async () => {


    const values = await page

      .locator('[data-testid="product-price"]')

      .allTextContents();


    return values.map(value =>

      Number(value.replace(/[^\d.]/g, ''))

    );


  };


  const firstPagePrices = await getPrices();


  await page.getByRole('button', {

    name: 'Next'

  }).click();


  const secondPagePrices = await getPrices();


  expect(firstPagePrices).toEqual([500, 1000]);


  expect(secondPagePrices).toEqual([1500, 2000]);


});

This test verifies that the first two pages display the expected prices in ascending order.

The sample assumes the test data and sorting rules are controlled. In production, use stable test data and wait for the page transition through a meaningful UI condition.

Step 5: Verify Sorting When Navigating Backward

Users should also be able to return to earlier pages without losing the selected sorting order.

test('Verify sorting after previous navigation', async ({ page }) => {


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


  await page.getByLabel('Sort by').selectOption('price-asc');


  await page.getByRole('button', {

    name: 'Next'

  }).click();


  await page.getByRole('button', {

    name: 'Previous'

  }).click();


  const prices = await page

    .locator('[data-testid="product-price"]')

    .allTextContents();


  const numericPrices = prices.map(price =>

    Number(price.replace(/[^\d.]/g, ''))

  );


  expect(numericPrices).toEqual([500, 1000]);


});

This checks whether the original first page is restored correctly.

Step 6: Verify Sorting When Changing Pages

Some applications reset the current page to page 1 when users change sorting options.

For example:

  1. Open page 3.

  2. Select Price: High to Low.

  3. Application resets to page 1.

  4. The highest-priced products appear.

Let's test that requirement.

test('Verify page reset after changing sort', async ({ page }) => {


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


  await page.getByRole('button', {

    name: '3',

    exact: true

  }).click();


  await page.getByLabel('Sort by').selectOption('price-desc');


  await expect(

    page.getByText('Page 1')

  ).toBeVisible();


});

This example is correct only when page reset is the application's intended behaviour.

If your application retains the current page after sorting, write the assertion according to that requirement instead.

Advanced Testing: Verify All Records Across Sorted Pages

A powerful combined test should verify the entire dataset, not just the first two pages.

The following example collects product prices across all pages and checks that the complete result is sorted.

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


test('Verify complete sorted product list', async ({ page }) => {


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


  await page.getByLabel('Sort by').selectOption('price-asc');


  const allPrices: number[] = [];


  while (true) {


    const values = await page

      .locator('[data-testid="product-price"]')

      .allTextContents();


    const currentPrices = values.map(value =>

      Number(value.replace(/[^\d.]/g, ''))

    );


    allPrices.push(...currentPrices);


    const nextButton = page.getByRole('button', {

      name: 'Next'

    });


    if (await nextButton.isDisabled()) {

      break;

    }


    await nextButton.click();

  }


  expect(allPrices).toEqual(

    [...allPrices].sort((a, b) => a - b)

  );


  expect(allPrices).toHaveLength(6);


});

This test verifies:

  • The sorting dropdown works.

  • Pagination works.

  • Sorting remains consistent across pages.

  • The complete list follows ascending order.

  • All six expected products are collected.

For a real project, also compare unique product IDs and expected product membership. Price-only validation cannot identify missing or duplicated products when multiple products have the same price.

How to Test Sorting and Pagination With Equal Values

Consider this product dataset:

Product

Price

Mouse A

₹500

Mouse B

₹500

Keyboard

₹1,000

Headphones

₹2,000

What happens when two products have the same price?

The application should ideally define a secondary sorting rule.

For example:

  1. Sort by price ascending.

  2. If prices are equal, sort by product ID ascending.

This is called a tie-breaking rule.

Why is it important?

Without a consistent secondary sort, records with equal values can move between pages when users navigate.

This may result in duplicate or missing products.

Your test should validate the application's agreed ordering rule, not assume that every database uses the same default order.

Common Bugs in Sorting and Pagination

Bug

Example

Testing approach

Sorting only current page

Page 1 sorted, page 2 unsorted

Compare complete result order

Duplicate records

Product appears twice

Compare unique IDs

Missing records

Some products disappear

Compare against expected dataset

Sorting reset

Next click removes sorting

Verify sort state after navigation

Incorrect page reset

Sorting changes but wrong page remains

Verify expected page state

Incorrect price order

₹5,000 appears before ₹500 in ascending mode

Compare numeric values

Unstable equal-value ordering

Records move between pages

Validate tie-breaking rule

Stale results

Old records remain after sorting

Verify updated records and state

Best Practices for Testing Sorting and Pagination

1. Test Both Features Together

Do not assume that successful independent tests guarantee successful combined behaviour.

2. Validate the Complete Dataset

Whenever practical, compare the entire sorted record set with the expected data.

3. Use Unique Identifiers

Product IDs, employee IDs and transaction IDs are more reliable than comparing names alone.

4. Verify Sorting State

After every navigation action, confirm that the selected sort option remains active if that is the expected behaviour.

5. Test Multiple Sorting Fields

Try sorting by:

  • Price.

  • Name.

  • Date.

  • Rating.

  • Status.

6. Check API and UI Behaviour

Use API testing to verify backend sorting parameters and returned records. Then verify that the frontend displays those records correctly.

Explore the Playwright API Testing guide.

7. Avoid Unnecessary Fixed Waits

Use Playwright's automatic waiting and meaningful assertions instead of adding fixed delays.

8. Keep Test Data Predictable

Use controlled datasets with known prices, names and unique IDs.

Frequently Asked Questions About Sorting and Pagination Testing

1. What is sorting and pagination testing?

Sorting and pagination testing checks whether a website correctly arranges records and displays them across multiple pages. It verifies that sorting remains consistent during page navigation.

2. How do you test sorting in Playwright?

Select the required sorting option, collect the displayed values, convert them into the correct data type and compare them against the expected ascending or descending order.

3. How do you test pagination after sorting?

Select a sorting option, navigate through multiple pages and verify that all displayed records follow the same sorting order.

4. Should sorting happen before pagination?

For most traditional paginated tables, yes. The application should sort the complete eligible result set before dividing it into pages. Otherwise, each page may be sorted independently, creating an incorrect overall order.

5. Why does sorting fail when clicking Next?

Possible reasons include incorrect backend query parameters, frontend state resets, inconsistent sorting logic, asynchronous updates or incorrect page offsets.

6. How do you test ascending and descending order?

Collect the displayed values and compare them against numerically or alphabetically sorted arrays. Use the correct comparison method for the data type.

7. What happens when multiple records have the same value?

The application should ideally use a stable secondary sorting field, such as a unique record ID, to maintain consistent ordering across pages.

8. Can Playwright test server-side pagination?

Yes. Playwright can interact with the UI while API requests are monitored or validated to confirm that the correct sorting and pagination parameters reach the backend.

9. Should sorting reset pagination to page 1?

Many applications reset to page 1 after sorting because the newly sorted records should start from the beginning. However, this is a product requirement, not a universal rule.

10. Is combined sorting and pagination testing necessary for e-commerce websites?

Yes. Customers frequently sort products by price, rating or popularity and navigate across pages. Testing both features together helps prevent incorrect product ordering and missing results.

Conclusion

Sorting and pagination are closely connected features in modern web applications.

A sorting feature may work correctly on the first page but fail when users navigate to the second or third page.

That is why automation testers should validate both features together.

With Playwright, you can automate ascending and descending sorting, page navigation, record validation, sorting persistence and complete dataset verification.

The most important principle is simple:

Do not just check whether records are sorted on one page. Check whether the complete result set remains correctly sorted across every page.

If you want to improve your practical skills in Playwright locators, assertions, API testing and framework development, explore the Playwright Automation Testing Course in Hyderabad.




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