Wait for before() to finish and use auth in tests

hi,

Actually two questions:

1.) In my before() function, i insert some users into my database via Factory

When the first test i create already needs this data from the database, it fail. Seems like the before() didn’t write to the database before the first test runs? how can i make sure the database is seeded before the first test runs?

2.) Also, how can i use auth.login() in my tests?

Hey @derTech! :wave:

  1. Could you paste the code of your before() function?

  2. You can take a look to this example: https://github.com/adonisjs/adonis-blog-demo/blob/master/test/functional/update-post.spec.js#L38

Sure, I simply setup two users and assign them roles:

before(async() => {
  Factory.model('App/Models/User').createMany('2',[{username: 'normaluser',
   email: 'normaluser@example.org',
   password: '1234'
  },
 {
   username: 'adminuser',
   email: 'adminuser@example.org',
    password: '4321'
 }])

Factory.model('Adonis/Acl/Role').createMany('2',[{
  name: 'Administrator',
  slug: 'administrator',
  description: 'Administrator Account'
},
{
  name: 'Free User',
  slug: 'freeuser',
  description: 'Free Users'
},
{
  name: 'Premium User',
  slug: 'premiumuser',
  description: 'Premium User'
}])

})

My test then fails when i want to call user.role() with 'Cant call role() on undefined). When i dont flush my mysql tables, and run the test a second time (ie, the data is already in the database when i start adonis test), it works fine.

You need to await your factory call.

1 Like

that was it. thank you very much.

Also my second question was answered with your link too. works perfectly.

1 Like