JS: Promise resolver is not a function

Viewed 17478

I'm trying to run this jestJS unit-test, but I do get TypeError: Promise resolver undefined is not a function. What am I doing wrong?

it('_onSubmit() should throw error if data is missing', (done) => {
  const createUserMutation = () => new Promise()
  const wrapper = shallow(<CreateAccount createUserMutation={createUserMutation} />)
  wrapper.update().find(Form).simulate('submit', {
    preventDefault: () => {}
  })
  createUserMutation.resolve().then(() => {
    expect(console.error).toHaveBeenCalled()
    done()
  })
})
2 Answers

new Promise() is trying to create a promise without an executor function*. The correct usage is to pass in a function that accepts up to two parameters (resolve and reject), e.g.:

var p = new Promise((resolve, reject) => {
    // ...code that does something, ultimately calls either resolve or reject
});

More on MDN:

Later, you appear to be trying to call resolve on the promise instance. You can't do that either (unless you're not using standard promises). You resolve a promise using the resolve function passed into the executor. (I tried to modify your code for you, but too much context info is required.)


* I'm surprised to see V8's error message say "resolver function" but I've verified it does. The spec calls it an executor, and I would have thought a "resolver functioN" would be the function the Promise constructor passes as the first argument to it...

If all you want to do is create a resolved promise, then use Promise.resolve(), which returns a new, already resolved promise.

new Promise() is for converting non-promise (usually asynchronous) code to promises, but it doesn't look like you need that here. If you were going to use it, you would have to pass a function into it (as Felix Kling and TJ Crowder have already noted).

Some more points:

  • You are defining createUserMutation as a function, so a few lines later when you use it, you would need to call it using (). Or you could choose to have it not be a function since it seems all you're trying to do here is produce a promise.
  • Also, as Felix Kling has pointed out, promises don't have a resolve() method. You can just call .then() on the promise produced by Promise.resolve().
Related