How to fake Ally in HTTP tests

When authenticating with Ally, my controller eventually calls:

  async loginOrCreate (ally, auth) {
    const ghUser = await ally.driver('github').getUser()

    // user details to be saved
    const password = this.generatePassword()

    const userDetails = {
      email: ghUser.getEmail(),
      token: ghUser.getAccessToken(),
      password: await Hash.make(password),
      social_login_source: 'github'
    }

    // search for existing user
    const whereClause = {
      email: ghUser.getEmail()
    }

    const user = await User.findOrCreate(whereClause, userDetails)
    await auth.login(user)
  }

I’m writing tests for this controller and I want to fake the Ally response so that I can test user creation. I’ve tried the ioc.fake() shown below but nothing still can’t seem to fake the data passed to the method shown above.

'use strict'
const { test, trait } = use('Test/Suite')('GitHub User Login'),
  /** @type {require('url')} */
  url = use('url'),
  { ioc } = use('@adonisjs/fold')


trait('Test/ApiClient')
trait('Auth/Client')
trait('Session/Client')

test('Create\'s user if not exist', async ({ assert, client }) => {
  ioc.fake('Adonis/Addons/Ally', () => {
    throw "Can I at least break the response?"
  })
  /**
   * @var {ApiClient} client
   * @var {require('../../app/Models/User')} User
   */
  const User = use('App/Models/User')
  /**
   * @type {VanillaSerializer}
   */
  const users = await User.all()
  const userCount = users.toJSON().length

  /** @type {ApiResponse} */
  const response = await client
    .get(`user/social-login/github/callback`)
    .end()

  // @todo create assertions
})

Hi @tylerssn, I had the same problem and I solved this using the nock, it intercepts the connection and you can simulate the response.

I hope this will help you

Faking social auth doesn’t make sense at all. Also writing an automated test for social auth isn’t possible, since it requires human consent.

I suggest writing post authorisation code inside a service, which the controller will use amd then test the service

1 Like