expect icon indicating copy to clipboard operation
expect copied to clipboard

Support tmatch in toHaveBeenCalledWith

Open jraede opened this issue 8 years ago • 4 comments

Is there a way to do something like this:

expect(mySpy).toHaveBeenCalledWith('foo', 'bar', anythingOfType(Function));

Seems like we would have to modify the isEqual test helper.

jraede avatar Jun 16 '16 21:06 jraede

How would "of type" be determined? instanceof is both unreliable and doesn't work cross-realm - this code is what's actually required to reliably determine that something is a function.

The only API i can think of that might work is one where the user decides for themselves - ie, anythingOfType would need to take a predicate function that received the value, and returned a boolean to indicate whether it passed. Thoughts?

ljharb avatar Jun 16 '16 22:06 ljharb

Yeah I think allowing a predicate function would be the most pluggable. In order to have the isEqual know whether to run the function or compare its equality we could add something like matchingPredicate(myPredicate) or matcher(myPredicate) which would return some sort of object that isEqual could recognize and run the predicate function.

It would be pretty cool to implement something like I did in simplecheck or just add support for that library, so we could do things like

expect(mySpy).toHaveBeenCalledWith('foo', 'bar', simplecheckMatcher({
     someProp: String,
     someOtherProp: oneOf(1, 2),
}));

jraede avatar Jun 17 '16 19:06 jraede

@jraede We already use tmatch under the hood in in toMatch. Maybe we could use it here as well? Seems like it does the same thing as simplecheck.

mjackson avatar Jun 29 '16 16:06 mjackson

The ability to do partial object checks with toHaveBeenCalledWith would be fantastic, so +1. Something like:

const obj = { a: 'a', b: 'b' };
const spy = expect.createSpy();
spy(obj);
expect(spy).toHaveBeenCalledWith({ a: 'a' })

ZephD avatar May 08 '17 10:05 ZephD