Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Click the column header, then assert that the displayed cell values are in the expected order. Also verify the sort indicator separately: an arrow can change even when the rows themselves are not sorted as the user sees them. The right assertion depends on whether the component reorders DOM nodes or represents visual order another way.

Write a basic sorting test

For an ordinary HTML table, scope the test to the table, click the target header, and read the relevant cells from its body. This example assumes the table has an accessible name and that the sortable header is a button; adapt those selectors to the markup your application actually renders.

it('sorts prices in ascending order', () => {
  cy.visit('/products')

  cy.findByRole('table', { name: 'Products' }).within(() => {
    cy.findByRole('button', { name: 'Price' }).click()

    cy.get('tbody tr')
      .then(($rows) => [...$rows].map((row) => {
        const cell = row.querySelector('[data-column="price"]')
        return Number(cell.textContent.trim().replace(/[$,]/g, ''))
      }))
      .then((prices) => {
        expect(prices).to.deep.equal([...prices].sort((a, b) => a - b))
      })
  })
})

The example assumes the displayed price can be converted to a number after removing dollar and thousands-separator characters. If your app formats prices differently, parse them according to its actual format rather than applying a conversion that silently produces invalid values. Cypress’s official Sorting the Table recipe demonstrates the same general pattern using an Ag-Grid example: scope to the grid, click the Price header, check the sort state, and compare extracted numeric values.

Check the sort state and the data separately

A visible ascending icon or an accessibility attribute can show what direction the header reports. The cell assertion checks whether the data actually follows that direction. Keep both checks when both behavior and control state matter; do not treat the icon alone as proof of sorted rows.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

For a semantic HTML table, sortable column headers should expose the current direction with aria-sort, as well as communicate it visually. See MDN’s aria-sort reference. Assert the accessibility contract your component implements; a custom grid may expose direction differently.

Choose the right order signal

When the DOM nodes are reordered

If sorting moves each row into its new position in the DOM, reading the relevant cells in row order is a suitable way to verify the displayed sequence. Query only the table or grid under test so unrelated cells elsewhere on the page cannot affect the result.

When visual order differs from DOM order

Some grids leave row elements in their original DOM positions and use CSS positioning to display them in a different sequence. In Cypress’s Ag-Grid recipe, rows were moved visually with translateY; a row-index attribute represented displayed position. A raw query of cells therefore returned DOM sequence, not visual sequence, and the test failed despite the grid appearing sorted.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

For that specific example, associate each value with its parent row’s index, sort the pairs by that index, then check the resulting values. Treat the Ag-Grid selectors and row-index as example-specific, not universal Cypress conventions:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.get('#myGrid').within(() => {
  cy.contains('.ag-header-cell-label', 'Price').click()

  cy.get('[col-id="price"].ag-cell')
    .then(($cells) => [...$cells].map((cell) => ({
      index: Number(cell.closest('[row-index]').getAttribute('row-index')),
      price: Number(cell.textContent.trim()),
    })))
    .then((items) => {
      const displayed = [...items]
        .sort((a, b) => a.index - b.index)
        .map((item) => item.price)

      expect(displayed).to.deep.equal([...displayed].sort((a, b) => a - b))
    })
})

Inspect the rendered output and component documentation to identify a stable signal for displayed position. A virtualized grid may render only some rows at a time, so a DOM query can describe the rendered subset rather than the entire dataset. In that case, test the user-visible rows the component currently renders or use a documented interface that exposes the order being displayed.

Normalize values before comparing them

JavaScript’s default Array.prototype.sort() sorts string representations, not numeric values. Thus, numeric-looking strings can end up in lexicographic order. Convert extracted values to numbers and supply a comparator for numeric ascending order:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const ascending = [...values].sort((a, b) => a - b)

MDN notes that sort() mutates the array in place and returns the same array. Copy the observed values with spread syntax when you need to retain their original sequence for a separate assertion. See MDN’s Array.prototype.sort() reference.

Choose normalization and comparison based on the column’s meaning:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Numbers: parse to numbers and use a numeric comparator. Handle currency symbols, grouping separators, and empty or unavailable values explicitly.
  • Dates: parse the displayed representation into comparable dates or timestamps using the format the application uses; do not rely on incidental string ordering unless the format is designed for it.
  • Text: compare strings using the same case and locale rules the product promises. If sorting is locale-sensitive, make the expected comparator reflect that contract.

Make the test deterministic and retryable

Give the test known initial data and make it runnable on its own. Do not rely on a preceding test to populate the table or leave it in a particular sort state. Cypress’s writing guide recommends independently passing tests, and end-to-end test isolation is enabled by default: Writing and Organizing Tests.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

A fixed .wait(1000) appears in the Cypress recipe to make the quick sort easier to demonstrate; it is generally unnecessary in a real test. Prefer Cypress assertions that retry until the expected state appears. Cypress describes queries as reading application state and retrying as needed in its API overview. For example, wait for the expected direction state with a retryable assertion, then make the data-order assertion against the rendered rows. Avoid waiting an arbitrary duration that may be too short on a slow run and waste time on a fast one.

Troubleshoot common failures

  • The ascending indicator appears, but the value assertion fails: First check whether the component changed visual position without reordering DOM nodes. Identify and assert its displayed-order signal instead of assuming query order equals screen order.
  • Values like 100 and 20 appear in the wrong numeric order: The extracted values may still be strings, or the expected array may use default sorting. Convert values to numbers and use (a, b) => a - b.
  • The assertion sees unrelated values: Scope the query with .within() to the intended table or grid and target the column’s cells specifically.
  • The assertion runs before sorting finishes: Replace a fixed wait with a retryable assertion for the sort state or expected order. Make sure the assertion observes the rendered UI state that changes when sorting completes.
  • Prices become NaN or comparisons behave unexpectedly: Inspect the actual cell text, including currency symbols, separators, whitespace, and placeholders. Normalize those deliberately and decide how blank or non-numeric cells should sort.
  • A test passes only after another test: Seed or arrange the initial data in this test and make its starting sort state explicit. Do not depend on state left by another test.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture the page rather than test Cypress sorting behavior, ScreenshotNeo can return a screenshot or PDF from one GET request. Its cleanup options accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with the response identifying page verdict and billing status. Its MCP server provides screenshot tools for AI agents, and the Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Every feature is on every plan.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://example.com 
  -o shot.webp

See the ScreenshotNeo API documentation for options and response details. ScreenshotNeo is made by Yorker Media. Sign up free for 1,000 screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does Cypress automatically sort table rows?

No. Cypress interacts with the page and verifies its behavior; the application or grid component implements sorting.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Should I assert ascending order before or after clicking a header?

That depends on the table’s initial sort state and click behavior. Arrange a known initial state, perform the user action, and assert the resulting direction and values.

Can I use ScreenshotNeo to verify a sorting test?

A screenshot can show what a page looked like at capture time, but it does not replace Cypress assertions over the sorted values or the component’s accessibility state.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.