Skip to content

Custom Jest Matcher

Joist provides a toMatchEntity matcher for more pleasant assertions in Jest.

There are two main benefits:

  • Asserting against a whole subtree of entities “as data”
  • Prettier actual vs. expected output

A potentially unwieldy pattern in tests is asserting against a “subtree” of entities, i.e. mapping each collection into POJOs, or asserting each entity one at a time:

const a1 = newAuthor(em, { books: [{ reviews: [{}] }, { reviews: [{}, {}] }] });
// Invoke something that changes the books' titles and the reviews' ratings
await updateBooksAndReviews(a1);
// Assert each piece individually
expect(a1.books.get.length).toEqual(2);
expect(a1.books.get[0].title).toEqual("b1");
expect(a1.books.get[0].reviews.get[0].rating).toEqual(5);

Instead, toMatchEntity provides a toMatchObject-style API so that a test can idiomatically declare what the subtree of data should be:

expect(a1).toMatchEntity({
books: [
{
title: "b1",
reviews: [{ rating: 5 }],
},
{
title: "b2",
reviews: [{ rating: 4 }, { rating: -2 }],
},
],
});

The upshot is that we get to assert against the entity “as if it’s JSON” or “just data”, and toMatchEntity takes care of unwrapping the references, collections, and properties, and comparing entities by identity (i.e. books: [b1, b2]).

Unlike .get, toMatchEntity includes soft-deleted entities in collections, so that a test sees the difference between “soft-deleted” and “removed”.

Sometimes when entities are included in Jest failures, i.e. by Jest’s native toMatchObject, the Jest console output is ugly b/c Jest prints the internal implementation of the entity object (i.e. a failure for “expected a1” ends up printing the a1.books field, which is actually a OneToManyCollection with various internal flags/state, all of which are included in the output).

Even with ~3-4 entities in a native toMatchObject assertion, the output can get long and hard to visually parse.

Instead, toMatchEntity abbreviates each entity as simply its tagged id, so output for an assertion failure of “the collection expected two books of b:1 and b:2 but only had one b:2” will look like:

- Expected - 0
+ Received + 1
Object {</>
"books": Array [
+ "b:1",
"b:2",
],
}
`);

Note that if an entity is new, i.e. the test has not done em.flush (which is fine, tests should only em.flush if really necessary, to be as fast & lightweight as possible), the abbreviation for an unsaved Book will be a “test id” of b#1 where b is the entity’s tag, and the #1 is the index of that particular entity within the EntityManager’s entities of that type.

In your setupTests.ts, add:

import { areEntitiesEqual, toMatchEntity } from "joist-test-utils";
expect.extend({ toMatchEntity });
// Optional, makes `toEqual` compare entities by identity
expect.addEqualityTesters([areEntitiesEqual]);