我正在为使用Gatsby
构建的客户网站编写单元测试。我需要能够提供100%的覆盖率。我无法对源代码进行重大编辑,因为我没有构建网站,也没有拥有代码,以免冒破坏 UI 的风险(我不做快照或 UI 测试(。
我一直在 Github 问题、堆栈溢出等中寻找答案,似乎在使用/* istanbul ignore next */
时反复出现一些特点。
使用 Gatsby,您必须检查任何脚本或 Web API 对window
的引用,如果typeof window === 'undefined'
,则有条件地忽略该代码,因为 Gatsby 在服务器上静态生成站点。为了增加这些语句、分支、函数和行的覆盖范围,我已经能够使用/* istanbul ignore next */
.但是,我在使用特定的类组件时遇到了困难。
我尝试在componentDidMount
componentDidUpdate
之前使用/* istanbul ignore next */
,并在生命周期定义中,在函数名称和括号之间,在生命周期内的if
块之前使用。我也尝试使用/* istanbul ignore if */
.
无论我使用什么代码,我都无法获得覆盖率。我愿意接受这里的任何建议,无论是使用ignore
语句的更好方法,还是关于创建测试的方法的提示。感谢您的帮助!
以下是组件的不可覆盖(到目前为止(行:
招贤纳士.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`,
})
}
}
我想我找到了一个有效的答案。
在 Jest 版本 26.0 的jest.config.js
中,您可以将coverageProvider
配置为babel
(默认(或v8
(被视为实验性(。
我更改为v8
并安装了v8-to-istanbul
:
npm i --save-dev v8-to-istanbul
这提供了一些新功能,似乎可以创造奇迹。除了functions
之外,我对所有内容都达到了 100% 的覆盖率。
/* 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()
}
}
}
/* 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`,
})
}
如果您遇到类似的问题,请查看此软件包:https://openbase.io/js/v8-to-istanbul/documentation#ignoring-the-next-line
此外,我找到了一种测试方法,该方法将script
附加到 DOM 中,componentDidMount
带有@testing-library/react
和jest
:
it(`adds script to body`, async () => {
render(<CareersWithProvider />)
const Grnhse = await waitFor(() => screen.findAllByTestId(`Grnhse`))
expect(Grnhse).not.toBeNull()
})