Testing function chains using Sinon.JS

71 views
Skip to first unread message

Ashutosh Tripathi

unread,
Jul 18, 2017, 8:25:09 AM7/18/17
to Sinon.JS

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.


Stackoverflow thread: https://stackoverflow.com/questions/45163530/testing-function-chains-using-sinon-js


Thanks!

Ashutosh Tripathi

unread,
Jul 21, 2017, 5:02:09 AM7/21/17
to Sinon.JS

For anyone who faces similar issues, I had to export out the Keycloak object from my method and then stub the init method on it.
Reply all
Reply to author
Forward
0 new messages