Rayrun
← Back to Discord Forum

How to assert that an array is equal to another?

For example, I want to test a sort button and check if the names are sorted in descending order. What would be the assertion method used? I am creating a copy of that array and sorting it with a .sort(), then comparing the two.

I was thinking .toBe() but there is also .toEqual() and I'm not sure which one to use?

This thread is trying to answer question "What assertion method should be used to check if an array is equal to another?"

0 replies

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.

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 luc@ray.run.