Replies: 1 comment 2 replies
-
Hey @nickabb! 👋🏻 That would be way easier to create an abstraction and change that abstraction during your test. You can follow the repository pattern, for example. class LucidUserRepository {
getAll() { return User.all() }
} const users = []
class InMemoryUserRepository {
getAll() { return users }
} abstract class UserRepository {
abstract getAll()
} Register inside a provider the abstraction you want to use: export default class AppProvider {
constructor(protected app: ApplicationContract) {}
public async boot() {
const LucidUserRepository = await import('infrastructure/repositories/user.lucid.repository')
this.app.container.bind('UserRepository', () =>
this.app.container.make(LucidUserRepository.default)
)
}
} Then inject the class using the IoC Container: @inject(['UserRepository'])
class UserController {
constructor (private repository: UserRepository) {}
index() {
return this.repository.getAll()
}
} Swap the implementation during testing: test.group('User', (group) => {
group.setup(() => {
Application.container.useProxies(true)
return () => {
Application.container.useProxies(false)
}
})
group.each.setup(async () => {
return () => Application.container.restore()
})
test('...', async ({ assert }) => {
Application.container.fake('UserRepository', () => {
return new InMemoryUserRepository()
}))
// ...
})
} This flow will be greatly simplified in V6. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'd like to be able to mock the AdonisJS models in order to not have to hit a live database for unit tests. I understand your comments on mocking - but I think we'll have to agree to disagree here - I'd still like to be able to do this in order to speed up tests.
Passing in each model as a parameter and then overriding them for tests works, but I'm trying to avoid that (this is the point of using an IoC container after all).
How can I do this?
Beta Was this translation helpful? Give feedback.
All reactions