Recipes
Small copy-paste friendly utilities
Last updated
Small copy-paste friendly utilities
Last updated
Moat Maker does not allow you to interpolate an object to compare by identity. If you want this behavior, you have to use a custom expectRef()
expectation as follows:
Comparing floats is dangerous - this includes any decimal number or number with a large magnitude (numbers outside of the to range). Due to minor rounding errors, they won't always compare when they should, like in this example:
You can use the expectCloseTo()
custom expectation to make sure a provided number is close to a target number, without requiring the two numbers to be exactly the same.
When you interpolate a class, it'll be used to check if a passed-in instance is an instance of that class, or of a derived class.
This is TypeScript's default behavior, but it might not be the behavior you want. If your end-users don't need the power of providing instances of derived classes to your API, you could choose to actively prevent it. This sort of prevention can be beneficial as it helps avoid internal details of your API from leaking out - think of end-users who override default methods with badly-behaving ones, and then minor updates to your library are released that cause their fragile methods to break. For many scenarios, it's overkill to worry about this sort of thing, but if you do wish to worry, expectDirectInstance()
is here to help.
Both the array and tuple validators permit sparse arrays to get through. Unless you specifically design to support sparse arrays, they can be dangerous and cause things to behave in unexpected ways. In most cases, you shouldn't need to worry about this problem (it's not common to see sparse arrays in practice, and in reality, there's never a time they should be used), but if you wish to actively prevent them from crossing your moat, expectNonSparse()
can help.
The use of this custom expectation is technically redundant if you're matching against an array/tuple rule that does not permit undefined
entries (holes are treated as undefined
during validation).
There are cases where you might want the match failure error message, without having to go through the trouble of catching and extracting the error message. The following helper function can be used to achieve this.
By default, Moat-Maker will throw an instance of TypeError
if the assertion fails. A TypeError
can also be thrown for other reasons, for example, if you pass in an invalid "at" or "errorPrefix" parameter into the .assertMatches()
function. For this reason, the above code sample tells Moat-Maker to throw an instance of a custom Error class to make sure we're only catching match failures and nothing else.