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.