Mock middleware


#1

I have middleware, see below, it just extend request and pass uid for specific controller. What I want is to mock this uid somehow for my tests.

Also there is a question about how to avoid verification itself for tests.

So I need mock uid and somehow avoid verification

class Auth {
  async handle ({ request }, next) {
    const token = request.header('authorization')

    const { uid, email } = await admin.auth().verifyIdToken(_.replace(token, 'Bearer ', ''))
    _.extend(request, {auth: {uid, email}})

    await next()
  }
}

I can resolve this, just generate dynamic token and pass it like this:

test('get list of posts', async ({ client }) => {
  const response = await client
    .get('/posts')
    .header('Authorization', 'Bearer <Dynamic Token>')
    .end()

  response.assertStatus(200)
})

But it seems a bad idea…

If u have some thoughts pls share it with me)


#2

Simply fake the middleware before the tests.

For example: Your middleware namespace is App/Middleware/Auth, simply create a fake for it

class FakeAuth {
   async handle (ctx, next) {
      next()
   }
}

ioc.fake('App/Middleware/Auth', function () {
  return new FakeAuth()
})

Since done with the tests, simply call restore to restore the fake

ioc.restore('App/Middleware/Auth')