Testing REST API and using ioc.fake


#1

Hi there! I tried to use ioc.fake in my function tests and I have met a problem where ioc.fake doesn’t work with REST API. Details:

// service
const Hashids = use('Hashids')

// model
class Account extends Model {
  static boot () {
    super.boot()

    this.addHook('beforeCreate', async (userInstance) => {
      userInstance.withNewPublicId()
    })
  }

  withNewPublicId () {
    this.publicId = Hashids.make() // just return 6 random letter + numbers

    return this
  }
}

// test case
test('create new account with duplicate publicId', async ({assert, client}) => {
  ioc.fake('Hashids', () => {
    return {
      make: () => 'aV1nI5'
    }
  })

  const user = await Factory.model('App/Models/User').create()
  const account = await Factory.model('App/Models/Account').create(data) // here I got 'aV1nI5' in publicId
  await userInstance.accounts().save(account)

  const response = await client // but there's no, here the service works usually
    .post('/api/v1/accounts')
    .loginVia(user)
    .send(credentialsForCreate)
    .end()

  ioc.restore('Hashids')
})