[expect] Allow creation of custom asymmetric matchers.
See original GitHub issue🚀 Feature Proposal
This is a dog food feature request for the expect
package.
Expect’s internal matchers are defined using a powerful but private API: classes extending AsymmetricMatcher
. While it is currently possible to import AsymmetricMatcher
from expect’s internal modules, it is not documented and expect.extend
does not understand matchers defined as AsymmetricMatcher
derivates. See this line where all non-internal matchers are assumed to be functions and wrapped in an AsymmetricMatcher.
I propose to document AsymmetricMatcher
, give it an export symbol from the expect
package, and modify expect.extend
to wrap function type matchers in CustomMatcher
(as is done already), while not performing any wrapping on matchers which extend AsymmetricMatcher
.
Motivation
Providing complex named assertion types is done to facilitate the best possible messages for developers (and non developers!) when things break. By allowing matcher authors to create new asymmetric matchers they can better fulfill their goals, making Jest more powerful (without being any more complex) for end users.
Example
I am building assertions helpers for iterators. For example, I would like create
expect(iterable).toBeIterable()
It should pass if Symbol.iterator
exists and is a function. not.ToBeIterable
should pass only if Symbol.iterator
does not exist.
Pitch
As proposed Jest API surface, this can’t NOT be in the core platform.
Issue Analytics
- State:
- Created 5 years ago
- Comments:24 (11 by maintainers)
Top GitHub Comments
OK here’s what I’ve got so far:
This code works, (succeeds and fails in the correct situations), however the failure message of the inner expect is lost. I don’t fully understand, from the perspective of Jest’s design, why the message would be discarded. I’m presuming it has to do with matching the Jasmine API.
Note: this required a Jest API change already in order for
argument.asymmetricMatch
to receive the variadic arguments passed toyields
.Hey guys, reanimating this old issue.
I came across this because I have this data structure (which I have already simplified for this issue):
So when I write my tests I want to see if my data matches my expected data:
So the problem is that I’d like to use an
asymmetric matcher
that I can use withinarrayContaining
. As I understand it, I could not just usejest.extend
because I could only write a custom matcher with that, likewhich would work on its own, but I could not do this:
right? So to validate a data structure like this I would need a mechanism to write a matcher that can be used alongside with
arrayContaining
orobjectContaining