Tillitsdone
down Scroll to discover

Custom Jest Matchers for Better Testing

Learn how to create custom Jest matchers to write more expressive and maintainable tests.

Discover advanced techniques for async testing and chainable matchers with practical examples.
thumbnail

A minimalist abstract composition showing geometric shapes like circles and rectangles interconnecting and overlapping representing testing and validation concepts using bold orange and blood red colors with sharp contrasts against a clean white background shot from straight above perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Custom Jest Matchers for More Expressive Tests

Writing clear and maintainable tests is crucial for any software project. While Jest provides a great set of built-in matchers, sometimes we need more specific assertions that better express our testing intentions. Let’s dive into creating custom Jest matchers that can make our tests more readable and maintainable.

Why Custom Matchers?

Imagine you’re testing a shopping cart functionality. You could write:

expect(cart.items.length).toBe(0);
expect(cart.total).toBe(0);

But wouldn’t it be nicer to write:

expect(cart).toBeEmpty();

This is where custom matchers shine – they help us write more expressive and domain-specific tests.

Abstract flowing lines forming a continuous path through space representing a seamless testing workflow using canary yellow and gradients of off-black captured from a low angle perspective with upward movement high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Creating Your First Custom Matcher

Let’s create a custom matcher that checks if an object has specific properties with certain types:

expect.extend({
toHavePropertyOfType(received, property, expectedType) {
const hasProperty = received.hasOwnProperty(property);
const propertyType = typeof received[property];
return {
pass: hasProperty && propertyType === expectedType,
message: () =>
`Expected object to have property "${property}" of type "${expectedType}", ` +
`but got ${hasProperty ? `type "${propertyType}"` : 'no such property'}`
};
}
});

Now we can use it like this:

expect(user).toHavePropertyOfType('age', 'number');
expect(product).toHavePropertyOfType('description', 'string');

Advanced Matcher Techniques

Let’s explore some advanced techniques for creating more powerful custom matchers.

Async Matchers

Sometimes we need to test asynchronous behavior:

expect.extend({
async toEventuallyHaveValue(received, expectedValue, timeout = 5000) {
const start = Date.now();
while (Date.now() - start < timeout) {
if (received.value === expectedValue) {
return {
pass: true,
message: () => `Expected value to eventually be ${expectedValue}`
};
}
await new Promise(resolve => setTimeout(resolve, 100));
}
return {
pass: false,
message: () =>
`Expected value to be ${expectedValue} within ${timeout}ms, but it wasn't`
};
}
});

Dynamic geometric patterns flowing through a cosmic environment featuring grapeseed and off-white colors against dark background shot from a diagonal perspective for depth high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Chainable Matchers

We can create more flexible assertions by making our matchers chainable:

expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling;
return {
pass,
message: () =>
`Expected ${received} to be within range [${floor}, ${ceiling}]`
};
}
});
// Usage
expect(price).toBeWithinRange(10, 20);

Best Practices

  1. Keep matchers focused and single-purpose
  2. Use clear, descriptive names
  3. Provide detailed error messages
  4. Document your custom matchers
  5. Share common matchers across your team

Conclusion

Custom Jest matchers are a powerful tool for creating more expressive and maintainable tests. By encapsulating complex assertions into simple, readable matchers, we can make our test suites easier to understand and maintain.

Remember, the goal is to make your tests as clear as possible – if you find yourself writing the same complex assertions repeatedly, it might be time to create a custom matcher!

Abstract architectural forms creating a sense of completion and harmony using perfect red and ochre colors with dynamic lighting captured from a bird's eye view perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/code-outline.svg Jest Blogs
Versatile testing framework for JavaScript applications supporting various test types.
icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.