更新第三方库时,Jest快照失败

bq3bfh9z  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(154)

我使用jest快照来测试我的react应用程序,每次更新组件库时,(带有compañy的通用react组件的包)所有测试都失败,因为包使用的classname包括其版本。例如,典型的classname看起来像lesson-card__1-7-0,1-7-0是组件库的版本。因此,每次生成快照时,它都包括库版本,当你把它更新到,比如说,1-7-1,每个测试filas。
该库在类名中包含版本,以避免在微服务使用不同版本的库时发生冲突。
所以,我想的选项是自定义toMatchSnapshot()方法,在比较时忽略版本。也许删除版本,这样快照就不会保存了。问题是自定义函数似乎不可能。
有谁知道我该怎么做吗?或者能想到其他的解决方案吗?提前谢谢你

kmbjn2e3

kmbjn2e31#

好了,我最终重新定义了de global expect jest函数:

const originalExpect = expect

// Match patterns of the form __3-4-5__ (including the underscores)
const toMatch = /__\d+-\d+-\d+__/g

// Each node of the tree has only 3 properties: a type, props and children.
// Inside the props it is the className, we remove substrings of the className
// using the match form. If the node has children, then we recursively walk through them.
function removeCLVersion(obj) {
    if (!obj || typeof obj !== 'object') return obj
    if ('props' in obj && 'className' in obj.props) obj.props.className = obj.props.className.replace(toMatch, '__')
    if ('children' in obj && obj.children) obj.children = obj.children.map(element => removeCLVersion(element))
    return obj
}

// Javascript functions cant be changed, so we are replacing it with a custom one that
// removes the CL version of the received object in the toMatchSnapshot method
global.expect = received => {
    const resultObject = originalExpect(received)
    resultObject.toMatchSnapshot = () => originalExpect(removeCLVersion(received)).toMatchSnapshot()
    return resultObject
}
// And then we add the methods of the original function to our new expect function
Object.assign(expect, {...originalExpect})

字符串
我在jest setupFilesAfterEnv中做了这件事。它可以用来重写expect result对象的任何方法。

相关问题