Skip to content

Custom Matchers

Latte provides a powerful way to create custom matchers, allowing you to extend the functionality of the built-in matchers to suit your specific testing needs.

This is particularly useful when you want to encapsulate complex assertions or when you want to create reusable matchers for your test suite.

Creating a Custom Matcher

If you miss the built-in matchers, you can easily create your own by extending an instance of Expect.

To create a custom matcher, you can extend Expect class.

import {Expect, messages} from "@olton/latte";
const customMessages = {
...messages,
toBeEven: {
positive: 'Expected value {received} not to be even',
negative: 'Expected value {received} to be even'
}
}
class MyExpect extends Expect {
toBeEven(msg) {
let received = this.received
let result = received % 2 === 0
this.assert(result, msg, 'toBeEven')
return this
}
}
const expect = (received) => new MyExpect(received, customMessages)
test(`Custom expect`, () => {
expect(2).toBeEven()
})
test(`Custom expect`, () => {
expect(3).not.toBeEven()
})