Rayrun
← Back to Discord Forum

Is there a way to assert whether or not a list of names are sorted in ascending/descending order?

For example, if there is a list of files on a website, would there be a way to assert whether the "sort" button works by checking if the list of file names are sorted in descending order?

This thread is trying to answer question "Is there a way to assert whether or not a list of names are sorted in ascending/descending order?"

2 replies

Take file names into an array. Then make another sorted array from those values and then make assertion comparing original array with sorted one if they match exactly.

I don't think playwright has built-in capability to do all of this, you'll probably need to do the coding in the middle part (making another sorted array)

Answer

Using Playwright's Assertion Methods to Check List Order

You can use Playwright's assertion methods to check if a list of names is sorted in ascending or descending order. Here's how:

Ascending Order

First, get a reference to your page object and locate your list element. Then, define an array of expected names in ascending order. Use the toHaveText assertion to check if the list elements match the expected names.

const page = await browser.newPage();
const nameList = await page.locator('ul > li');
const expectedNamesAscending = ['Alice', 'Bob', 'Charlie'];
await expect(nameList).toHaveText(expectedNamesAscending);

If the elements match 'Alice', 'Bob', and 'Charlie' in this exact order, the assertion will pass. If not, it will fail.

Descending Order

For descending order, define an array of expected names in descending order. Use the toHaveText assertion to check if the list elements match these names.

const expectedNamesDescending = ['Charlie', 'Bob', 'Alice'];
await expect(nameList).toHaveText(expectedNamesDescending);

If the elements match 'Charlie', 'Bob', and 'Alice' in this exact order, the assertion will pass. If not, it will fail.

So, with Playwright's toHaveText assertion, you can easily check if a list of names is sorted in ascending or descending order.

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].