2

我在弄清楚如何为我的一些 JS 代码提供代码覆盖率时遇到问题,其中一个函数调用了以回调为参数的第 3 方函数:

  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
  }

我使用 AVA 和 Sinon 进行单元测试,使用 Auth0 进行身份验证。下面的auth.parseHash函数调用是对 auth0.js 库函数的调用,该函数接受自定义回调。但是对于我的生活,我无法弄清楚如何以涵盖下面所有代码的方式来存根函数。例如,我可以为auth.parseHash创建一个存根,为我的回调函数创建一个存根。但是代码覆盖并没有覆盖条件逻辑中的内部语句,因为我的回调只是一个存根。如果我将回调模拟为接近实际代码的内容,代码覆盖率仍然无关紧要。

我的总体问题是,我做错了吗?这是糟糕的代码设计吗?在这种情况下是否有任何标准模式可以遵循?

非常感谢我能得到的任何帮助。先感谢您。

4

0 回答 0