I am writing some tests in Loopback 4 and I need to mock / stub a service, I mean I need to replace it in bindings by a stub one. But I can't find how to do this.
I want to write tests such as this one :
it(`should work if a user was found for the token in 'authorization' header`, async () => {
await client
.get('/mock')
.set('Authorization', 'Bearer a-good-token')
.expect(200);
});
For this I have to start an application before each test suite in before
method.
I boot my application then I try to change the binding for my service :
before('setupApplication', async () => {
app = new MyApplication();
await app.boot();
app.bind('services.WebAuthService').to(MockWebAuthService); // to replace with the mocked one
app.controller(MockController);
await app.start();
}
I tried different ways to write my MockWebAuthService :
- With Sinon stub :
const utilisateur = sinon.createStubInstance(Utilisateur);
utilisateur.uId = 123456;
const verifyCredentialsStub = sinon.stub().resolves(undefined);
verifyCredentialsStub
.withArgs({token: 'a-good-token'})
.resolves(utilisateur);
const MockWebAuthService: WebAuthService = sinon.createStubInstance(
WebAuthService,
{
verifyCredentials: verifyCredentialsStub,
convertToUserProfile: sinon.stub(),
},
);
- Or with a new class :
class MockWebAuthService implements UserService<Utilisateur, Credentials> {
async verifyCredentials(credentials: Credentials): Promise<Utilisateur> {
const utilisateur = sinon.createStubInstance(Utilisateur);
utilisateur.uId = 123456;
if (credentials.token === 'a-good-token') {
return utilisateur;
} else {
throw new Error('invalid token');
}
}
convertToUserProfile(utilisateur: Utilisateur): UserProfile {
return {} as UserProfile;
}
}
But none of these works. The WebAuthService
that is injected in my components is still the one from src/services
, not the mocked one.
Any idea how I should do that ?
Thanks in advance for your help !