Jest.js error: "Received: serializes to the same string"

Similarly to other colleagues I had this issue with an Array comparison, I was basically testing a function that got the largest string in an array, additionally it should return an array if more than 1 of those strings matched the largest length possible.

When I started testing I got the following message:

screenshot of jest results

So I replaced the toBe method

expect(function(array1)).toBe('one result')

with toStrictEqual to make a deep equality comparison

expect(function(array2)).toStrictEqual(['more than one', 'more than one']);

Just had this problem when tried to compare arrays where in one array there was an element with -1 index set (imagine any other key to be set except numbers from 0 to N). So you may have this error in the following scenario:

const arr = [1, 2]
arr[-1] = 'foo'
expect(arr).toEqual([1, 2])

They both serialized to the same string, but they are not equal.


I had a similar case where the object had a base64 encoded string, I managed the test to compare the serialization of the object using JSON.stringify:

expect(JSON.stringify(newDeal)).toMatchObject(JSON.stringify(expected));