How can I test a function like the following using Sinon.JS?
export function getToken(done) {
const kc = Keycloak(config)
kc.init({ onLoad: 'login-required' })
.success(authenticated => {
authenticated ? done(null, kc.token) : done(new Error('Some error!'), null)
})
.error(() => {
done(new Error('Some error'), null)
})
}
I tried doing something like the following, to no avail:
it('should return access_token', () => {
const mockKeycloak = sinon.stub(Keycloak, 'init').returns({
success: () => (true)
})
getToken(function () {})
expect(mockKeycloak.callCount).to.equal(1)
})
Basically Keycloak from keycloak-js is an IIFE but even after trying to stub the Keycloak
object on the window reference, I can't make it to work.
For anyone who lands here, this is what I did:
Since Keycloak is an IIFE, it overrides the stubbed object once we do
const kc = Keycloak(config)
Therefore I just exported this object kc
from the source and stubbed the init
method on it and it worked just fine!