我如何对具有 document.querySelector 的函数进行单元测试?

时间:2021-04-09 02:17:42

标签: javascript node.js reactjs jestjs enzyme

export function getNavHeight() {
  const merchantNav = document.getElementById(
    'merchant-header-main-wrapper-internal'
  )
  const dw2Nav = document.querySelector('.cw_navbar__mainnav')
  let navHeight = 72 // Consumer header is fixed to 72
  if (merchantNav) {
    navHeight = merchantNav.offsetHeight
  }
  if (dw2Nav) {
    navHeight = dw2Nav.offsetHeight
  }
  return navHeight
}

上面的块是我想为其编写单元测试的函数,我们使用的是 Jest,我们的应用程序主要是用 React 编写的。使用这个函数是因为我们有一些其他的客户端脚本被调用来渲染不同的导航,所以我们使用这个函数来确定导航高度。 测试这个的最好方法是什么?我是测试新手,因此非常感谢您的帮助。

我对如何创建“Fake Dom”并使用不同的 className 插入不同的 Nav 以测试结果感到困惑

1 个答案:

答案 0 :(得分:0)

您只需要mock document.querySelector