I have an API built with Adonis 5 (core version 5.4.0). The tests are made with Adonis' own runner, japa (version 3.1.1).
As per the Adonis documentation, I build my tests to interact with a real test database without mocks. However, we implemented a functionality which calls a third party API using HTTP requests and need to write tests for that. Naturally, the tests should not actually call this third party API and must be mocked.
I'm having difficulties setting mocks in the tests as japa does not seem to have a way to do this and there's no mention of it in the documentation. The best I could come up with was seeing that Adonis 4 uses an adonisjs/fold package to build mocks and tried doing the same, but to no results.
Here's an example of what I tried with adonis/fold version 8.1.9, but using a login method for simplification:
// in App/Services/AuthService
export default class AuthService {
public static async userLogin(email: string, password: string) {
// Authentication logic
return {
token: 'realGeneratedToken'
}
}
}
// In AuthService.spec.ts
test('It should login user using mock', async (assert) => {
const ioc = new Ioc()
ioc.useProxies(true)
ioc.fake('App/Services/AuthService', () => {
return {
async userLogin(email: string, password: string) {
return {
token: 'mocked token',
}
},
}
})
const { status, body } = await supertest(BASE_URL).post(LOGIN_URL).send({
email: 'any@email.com',
password: 'any_password',
})
assert.equal(status, 200)
assert.equal(body.token, 'mocked token')
ioc.restore('App/Services/AuthService')
})
This does not work. The real method is called, but there are no errors by using fold in the test, either.
Does anyone know how to set up mocks in Adonis 5 tests? Is using adonisjs/fold the correct approach?