2

I have a problem figuring out how to provide code coverage for some of my JS code where a function has within it a call to a 3rd party function that takes a callback as a parameter:

  function handleAuthentication () {
    let path = auth.parseHash(window.location.hash, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        // console.log('first it goes in here for new session')
        // pop toaster when use logs in
        logger.popToaster({
          title: 'Welcome!',
          desc: 'This is STRAP'
        }, 'success')

        setSession(authResult)
        return '/home'
      } else {
        // console.log('OR it goes in here for new session')
        if (err) {
          console.log('but never here!')
          // pop toaster if something goes wrong during login
          logger.popToaster({
            title: 'Something Went Wrong!',
            desc: `Error: ${err.error}. Check the console for further details.`
          }, 'error')

          console.log(`Error: ${err.error}. Check the console for further details.`)
        }

        return '/login'
      }
    })

    return path
  }

I'm using AVA along with Sinon for unit testing, and Auth0 for authentication. The auth.parseHash function call below is a call to an auth0.js library function which takes in a custom callback. But for the life of me I can't figure out how to stub the function in a way that covers all my code below. So for example, I can create a stub for auth.parseHash and a stub for my callback function. But code coverage doesn't cover the inner statements within the conditional logic as my callback is just a stub. And if I mock my callback to something close to the actual code, code coverage still doesn't care.

My overall question is, am I doing this all wrong? Is this bad code design? Are there any standard patterns to follow in cases like these?

Really appreciate any help I can get. Thank you in advance.

user2360062
  • 663
  • 2
  • 7
  • 19
  • WOW! Not a single semicolon. – Alan Larimer Sep 26 '17 at 17:44
  • I'm using ES6 with ESLint plugin which complains and throws an error when using ;. I'd imagine during the application transpilation -> ES5, the ; are added in. – user2360062 Sep 26 '17 at 17:49
  • Add a stub only for auth.parseHash in wich you call your callback with arguments setted with values to reach the line of code you want test. You must not create a stub for the callback itself because this is what you should test – Troopers Sep 27 '17 at 06:47
  • Thanks @Troopers. That's essentially what i had to do. The issue turned out to be that using sinon.stub() wasn't doing the trick. I had to create a custom stub for parseHash(and for that matter, any other function i'm testing). Then I can pass certain params and tell the stub to behave according to those params, thereby testing multiple paths through the function (success, error, etc). – user2360062 Sep 27 '17 at 13:29

0 Answers0