🎄 Get 50% off from our JavaScript course for the holidays! 🎄

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

Ferenc Almasi • 2022 November 08 • 📖 1 min read

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:

// ❌ 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
Copied to clipboard!

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.

// ✔️ 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
Copied to clipboard!
Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

🎉 Thank you for subscribing to our newsletter. x