Rayrun

How do I compare two arrays for equality in Playwright tests?

Answer

Comparing Arrays in Playwright Tests

When you're testing with @playwright/test, you might need to compare two arrays. Playwright provides the toEqual method for this. It performs a deep equality check, comparing the contents of the arrays, not just their references.

Here's an example:

const array1 = [1, 2, 3];
const array2 = [1, 2, 3];

expect(array1).toEqual(array2);

In this code, toEqual compares each element of array1 with its corresponding element in array2. If all elements are equal and in the same order, the test passes.

Remember, toEqual checks that both arrays have exactly the same number of items and each item is checked recursively. This means that nested objects or arrays within the main array will also be compared for equality.

If you only need to check if two arrays have matching items, but not necessarily in the same order, you can use toContainEqual. This method checks if an expected value exists within a collection.

const array1 = [{ name: 'John' }, { name: 'Jane' }];
const array2 = [{ name: 'Jane' }, { name: 'John' }];

expect(array1).toContainEqual({ name: 'Jane' });
expect(array2).toContainEqual({ name: 'John' });

In this case, each object is checked individually for equality using a "deep equality" comparison, even though the objects are in different orders in the arrays.

So, depending on your needs, you can use toEqual or toContainEqual to compare arrays in your Playwright tests.

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