无法忽略在获得覆盖范围的情况下发生伊斯坦布尔忽略的React类组件中的块

我正在为使用Gatsby构建的客户网站编写单元测试。我需要能够提供100%的覆盖率。我无法对源代码进行重大修改,因为我没有构建网站,也不拥有代码,以免冒着破坏UI的风险(我不进行快照或UI测试)。

我一直在Github问题,堆栈溢出等问题中寻找答案,而且似乎在使用/* istanbul ignore next */时经常出现特殊情况。

使用Gatsby时,您必须检查所有脚本或Web API对window的引用,如果是typeof window === 'undefined',则必须有条件地忽略该代码,因为Gatsby是在服务器上静态生成站点的。为了增加对这些语句,分支,函数和行的覆盖范围,我已经能够使用/* istanbul ignore next */。但是,我在使用特定的类组件时遇到了麻烦。

我尝试在生命周期内/* istanbul ignore next */块之前的componentDidmountcomponentDidUpdate之前,在函数名称和括号之间的生命周期定义中使用if。我也尝试过使用/* istanbul ignore if */

无论我使用什么代码,我都无法覆盖。我愿意接受这里的任何建议,无论是使用ignore语句的更好方法,还是有关创建可实现此目的的测试的提示。谢谢您的帮助!

以下是该组件无法发现的行(到目前为止):

careers.js

  componentDidmount() {
    this.context.setHeaderTheme(`bright`)
    /* istanbul ignore next */
    if (typeof window !== `undefined` && typeof document !== `undefined`) {
      if (!window.Grnhse) {
        const script = document.createElement(`script`)
        script.setattribute(
          `src`,`<hidden/path/for/security/purposes>`
        )
        script.setattribute(`width`,`100%`)
        script.onload = () => window.Grnhse && window.Grnhse.Iframe.load()
        document.body.appendChild(script)
      } else {
        if (window.Grnhse) {
          window.Grnhse.Iframe.load()
        }
      }
    }
  }

  componentDidUpdate() {
    /* istanbul ignore next */
    if (
      !this.scrollDone &&
      typeof window !== `undefined` &&
      window.location.search.includes(`gh_jid`) &&
      this.greenhouseContainer
    ) {
      this.scrollDone = true
      window.scrollTo({
        top: this.greenhouseContainer.offsetTop,behavior: `smooth`,})
    }
  }  
iCMS 回答:无法忽略在获得覆盖范围的情况下发生伊斯坦布尔忽略的React类组件中的块

我想我找到了一个有效的答案。

在Jest 26.0版的mtcars中,您可以将jest.config.js配置为coverageProvider(默认)或babel(考虑为实验性)。

我更改为v8并安装了v8

v8-to-istanbul

这提供了一些新功能,这些功能似乎可以发挥作用。除了npm i --save-dev v8-to-istanbul 之外,我几乎覆盖了所有内容。

functions
    /* c8 ignore next 16 */
    if (typeof window !== `undefined` && typeof document !== `undefined`) {
      if (!window.Grnhse) {
        const script = document.createElement(`script`)
        script.setAttribute(
          `src`,`...`
        )
        script.setAttribute(`width`,`100%`)
        script.onload = () => window.Grnhse && window.Grnhse.Iframe.load()
        document.body.appendChild(script)
      } else {
        if (window.Grnhse) {
          window.Grnhse.Iframe.load()
        }
      }
    }

如果遇到类似问题,请签出此软件包:https://openbase.io/js/v8-to-istanbul/documentation#ignoring-the-next-line

此外,我发现了一种方法,用于测试 /* c8 ignore next 13 */ if ( !this.scrollDone && typeof window !== `undefined` && window.location.search.includes(`gh_jid`) && this.greenhouseContainer ) { this.scrollDone = true window.scrollTo({ top: this.greenhouseContainer.offsetTop,behavior: `smooth`,}) } 是否通过scriptcomponentDidMount附加到@testing-library/react上的DOM:

jest
本文链接:https://www.f2er.com/2089586.html

大家都在问