This is more of a question than a bug or feature request but what would be the best practice for writing unit tests for an Adonis project Repository, Service, etc module? I ask this because if one of those classes has a use() statement the unit test will fail since use is not defined.
I could bootstrap the framework before the unit tests are ran but that seems like a lot of overhead. Alternatively, I could mock the use method but then finding the appropriate project or framework files may be tricky as well.
Both are doable but I wanted to get advice on what might be the best scenario.
Ideally you have to load providers and the IoC container before running your tests. Think of it as a startup script to run your tests and their is nothing wrong about it. A general idea of writing tests is to get the world setup and with AdonisJs, the world is the setting up providers.
Also if you want more control over tests, you should make use of Dependency Injection, instead of making use of use.
class UserController {
static get inject () {
return ['App/Model/User']
}
constructor (User) {
this.User = User
}
* index (request, response) {
const users = yield this.User.all()
response.json(users)
}
}
Now if you want, you can test UserController without the model, since it is injected in the constructor.
Going to close it for now. Feel free to share your ideas or questions you have
Thanks for the clarification! That helps a lot. I'll let you know if I come across any other questions or concerns.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Ideally you have to load providers and the IoC container before running your tests. Think of it as a startup script to run your tests and their is nothing wrong about it. A general idea of writing tests is to get the world setup and with AdonisJs, the world is the setting up providers.
Also if you want more control over tests, you should make use of Dependency Injection, instead of making use of
use.Basic DI example with Controllers
Now if you want, you can test
UserControllerwithout the model, since it is injected in the constructor.