How to Fix "serializes to the same string" Errors in Jest
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({})
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))
π More Webtips
Master the Art of Frontend
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions
Courses

JavaScript Unit Testing
The Practical Guide
Learn how to write automated tests (unit and integration tests) for your JavaScript projects with Vitest and Jest.

Unit Testing for TypeScript and Node.js Developers
With Jest
Master unit testing with Node.js, Typescript, Jest, and React. Write top-quality Typescript and Node.js software with Jest.

Testing Next.js Apps with Jest
Plus Testing Library and Cypress
Learn to test a real-world serverless React app with routes, authentication, database, and more!