The wrong thing with AdonisJs testing approach

#1

When testing, let us say, a POST request, we have to produce an instance of the Lucid model under testing through Factory:

const myModelInstance = await Factory
  .model('App/Models/MyModel')
  .create()

As advertised on the documentation and here, from there, we check what we want on the myModelInstance.

This is a nasty approach because it means each time we run the tests, we have to dump the database with fake data that can spoil completely our business.

Do you have a cleaner alternative to share?

Thanks,
Billal BEGUERADJ

0 Likes

#2

Hello Billal,

I guess there are two different ways which we can use in this case. First, we can create only unit tests. You may check out the documentation about it in order to get more information. When we write a unit test, it means that we don’t have a real connection with the database or even file system. With unit test, we test only units. In your code example, it is not unit test anymore because your are really connecting the database.

The second way is creating a test environment. In .env.testing file, I choose sqlite as DB_CONNECTION. Also in vowfile.js, I delete the sqlite file for every test execution. So I have a clear database for every time and I can execute even migrations.

module.exports = (cli, runner) => {
  runner.before(async () => {

    // We should delete dummy database for every test execution.
    if (fs.existsSync('./testing.sqlite')) {
      fs.unlinkSync('./testing.sqlite')
    }

    use('Adonis/Src/Server').listen(process.env.HOST, process.env.PORT)

    await ace.call('migration:run')
  })

  runner.after(async () => {
    use('Adonis/Src/Server').getInstance().close()
  })
}

This is the scenario which I use. I hope it can help.

1 Like

#3

Your approach has the advantage of not messing up with the real database; its disadvantage come when we have a lots of tests: that will at least lead to tests taking long time to run (since they involve calls to a physical database)

Usually we mock the database calls, but I did not implement this concept in AdonisJs yet.

Thank you for sharing your idea.

1 Like

#4

You are right @begueradj . I have seen Fakes at the documentation but I guess it doesn’t cover database. We should be able to mock database connection.

1 Like