Rayrun

What methods can I use in Playwright to assert an array in a test when the elements are not in the same position?

Answer

Asserting Arrays in Tests with Playwright

When testing with @playwright/test, you might need to assert arrays where elements aren't in the same position. Here's how you can do it.

Using toHaveText

Playwright's LocatorAssertions class provides a method called toHaveText. This method checks if a locator points to elements with specific text values. Here's how you can use it:

await expect(page.locator('ul > li')).toHaveText(['Text 1', 'Text 2', 'Text 3']);

This will pass if the <li> elements have the text values "Text 1", "Text 2", and "Text 3" in any order. If you want to assert a specific order, provide the expected text values in that order:

await expect(page.locator('ul > li')).toHaveText(['Text 3', 'Text 2', 'Text 1']);

Using toContainEqual

If you only want to assert that certain items exist within an array without considering their positions, you can use toContainEqual from GenericAssertions. This method checks if a collection contains an object with properties matching those of your expectation. Here's an example:

const value = [
   { example: 1 },
   { another: 2 },
   { more: 3 },
];

expect(value).toContainEqual({ another: 2 });

This will pass because there is an object within value that has a property named "another" with a value of 2.

In summary, toHaveText and toContainEqual are powerful tools for accurate and detailed assertions in your tests. Happy testing with Playwright!

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

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].