πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.

How to Fix "serializes to the same string" Errors in Jest

Ferenc Almasi β€’ 2022 November 08 β€’ Read time 1 min read
  • twitter
  • facebook

The "serializes to the same string" error happens in Jest when you try to expect an object to match a certain value, but you are using the wrong matcher. For example, you might have one of the following in your test case:

Copied to clipboard! Playground
// ❌ Both of these examples will throw "erializes to the same string"
// Usin an array
expect([]).toBe([])

// Using an object
expect({}).toBe({})
Test throwing "serializes to the same string" error

In its simplest form (using an empty array or object), this test won't pass. This happens because each object reference is different in JavaScript. There are several ways to get around this. Use one of the following matchers in order to fix the error.

Copied to clipboard! Playground
// βœ”οΈ This will work
const expected = []
const actual = []

// Using other matchers
expect(actual).toStrictEqual(expected)
expect(actual).toMatchObject(expected)

// Converting to a string
expect(JSON.stringify(actual)).toEqual(JSON.stringify(expected))
Using correct matchers for checking object equality
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.