> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/javascript/define-a-custom-jest-matcher.md).

# Define A Custom Jest Matcher

Though [Jest's built-in matchers](https://jestjs.io/docs/en/expect) will get you pretty far in most testing scenarios, you may find yourself in a testing situation better served by a custom matcher. Custom matchers can be defined using the [`expect.extend()` function](https://jestjs.io/docs/en/expect#expectextendmatchers).

Here is an example of a matcher that can check equality of two objects based solely on their `id` property.

```javascript
expect.extend({
  toHaveMatchingId(recieved, expected) {
    const pass = recieved.id === expected.id;

    if (pass) {
      return {
        pass: true,
        message: () =>
          `expected id:${expected.id} to not match actual id:${recieved.id}`
      };
    } else {
      return {
        pass: false,
        message: () =>
          `expected id:${expected.id} to match actual id:${recieved.id}`
      };
    }
  }
});
```

This defines the name of the matcher (`toHaveMatchingId`), contains some logic to figure out whether `received` and `expected` pass the matcher, and then two return conditions (`pass: true` and `pass: false`) with accompanying message-returning functions.

It can then be used like any other Jest matcher:

```javascript
test("compare objects", () => {
  expect({ id: "001" }).toHaveMatchingId({ id: "001" });
  // ✅
  expect({ id: "001" }).toHaveMatchingId({ id: "002" });
  // ❌ expected id:002 to match actual id:001
});
```

Check out a [live example](https://codesandbox.io/s/focused-bush-vw2s5).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/javascript/define-a-custom-jest-matcher.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
