testdouble.js icon indicating copy to clipboard operation
testdouble.js copied to clipboard

support promises resolve/reject

Open searls opened this issue 11 years ago • 7 comments

I got an email asking for promise support. I didn't think hard about it because I don't have an immediate need.

What if we had this API?

td.config(promiseProvider: someFuncThatCreatesPromises)

td.when(...).thenResolve(someValue)
td.when(...).thenReject(someOtherValue)

And then maybe on the verification side?

td.verify.resolved(value)
td.verify.rejected(someOtherValue)

I don't use promises much and I generally don't TDD with them in mind (since I try to keep async stuff to the periphery of my app where I'm integrating with stuff). Any thoughts on how to go about this or what an example test would look like?

Paging @jasonkarns as he's my promise whisperer

searls avatar Nov 02 '15 14:11 searls

I'm still back and forth on this. Going to keep chewing on this post 1.0.0

searls avatar Mar 10 '16 06:03 searls

Essentially that would be a shortcut for td.when(...).thenReturn(Promise.resolve(someValue)).

The problem with this is: what is Promise? On more recent node versions it is built-in, but older ones would fail unless polyfilled and the same is true for browsers. Then there are also libraries like RSVP.js that offer a Promise with additional functionality like a finally() method, which is however not attached to the global object.

To support these cases it would probably make sense to add a second, optional parameter to thenResolve/Reject() for passing in the Promise class. If not specified it would then use the built-in one.

Turbo87 avatar Mar 22 '16 16:03 Turbo87

@Turbo87, yes, if this is implemented then the behavior would be:

  1. If no native Promise is found, raise an error
  2. If a top-level Promise function is found, use that as the constructor
  3. If the user has set td.configure({promiseConstructor: SomePromiseFunc}), then use that, regardless of whether a native one is found.

searls avatar Mar 30 '16 17:03 searls

This interface sounds really useful - setting up doubles for Promises takes a bit of boilerplate.

Is it planned for any time soon? Are you happy with the proposed interface, and accepting PRs?

rowanu avatar Jun 09 '16 02:06 rowanu

@rowanu yeah, I'm open to seeing a PR on this.

searls avatar Jun 09 '16 08:06 searls

I've started working on this issue. See the progress in my fork. Currently, only native Promise is supported.

mgryszko avatar Jun 23 '16 20:06 mgryszko

Thanks @mgryszko -- I don't think I can merge unless we make the Promise constructor configurable. Sadly we live in the era of transpilers & polyfills and I don't know anyone in practice who uses the native Promise object in production

searls avatar Jun 24 '16 17:06 searls