Search code examples
unit-testinghapi.js

HapiJS reply being called twice


I'm getting this error message with the snippet below

Unhandled rejection Error: reply interface called twice

Note that I'm using return for all the reply() interface

Locations
    .findOne({
      _id: request.params.id,
      activationCode: payload.activationCode
    }).then((location) => {
      if (!location) {
        return reply(Boom.notFound('Location not found'))
      }
      locationObject = location
      if (payload.password !== payload.confirmPassword) {
        return reply(Boom.badRequest('Password and Confirm Password must match'))
      }
      if (!payload.terms) {
        return reply(Boom.badRequest('Must agree to Terms & Conditions'))
      }
      return newPaymentMethod.save()
    }).then((paymentMethod) => {
        .....
        return user.save() // user is defined at .....
    }).then(() => {
      return reply({ token: helpers.createJwt(userObject) })
    }).catch((err) => {
      return reply(Boom.wrap(err))
    })

Solution

  • Looks like you get caught into this due to the incorrect use of promises. I guess you’re executing your snippet within a route handler where you’ve access to reply.

    As you’re returning your responses within the promise chain, you both return the value to the next .then (promise) and also calling the reply from the outer scope.

    I suggest you use a promise reject for errors so that you only need a single reply(Boom.method()) within the promise’s .catch().