【问题标题】:How to use Jest/Enzyme to test React components with JSS style encapsulation?如何使用 Jest/Enzyme 测试带有 JSS 风格封装的 React 组件?
【发布时间】:2018-03-31 05:44:55
【问题描述】:

由于 JSS 组件封装,我在使用 Jest 测试我的 React 组件时有些吃力。

伪代码示例:

JSS(style.js):

export default {
    pinkOnYellow: {
       color: 'pink',
       backgroundColor: 'yellow'
    }
}

反应组件

import { withStyles } from 'material-ui/styles'
import compose from 'recompose/compose'
import classes from './style.js'

const MyComponent = ({classes}) =>{
   <div className={classes.pinkOnYellow} />
}

export default compose(withStyles(style))(MyComponent)

当组件被实例化时,classes 对象看起来有点像:

{pinkOnYellow: 'MyComponent-pinkOnYellow-32423'}

因此组件 HTML 看起来像

<div class="MyComponent-pinkOnYellow-32423" />

这意味着在编写 Jest/Enzyme 测试时我不能轻易使用类选择器,因为我不知道类名映射到什么。 我找到了一些解决方案,但我对这两种方法都不满意,因为它们都非常严格:

第一个

it('should be shallow as my soul', () => {
   const imageGallery = shallow(<ImageGallery images={images} />)
   expect(timageGallery.find('[class^=pinkOnYellow]')).toBe(1)
})

第二个(不适用于浅层)

function getClassesByEnzymeInstance(instance, className) {
   const componentName = instance.name()
   const classNameMapped = `.${instance.find(componentName).props('classes').classes[className]}`
   return classNameMapped
}

it('should be not as shallow', () => {
   const imageGallery = mount(<ImageGallery images={images} />)
   const mappedClassName = getClassesByEnzymeInstance(ImageGallery, 'pinkOnYellow')
   expect(timageGallery.find(mappedClassName)).toBe(1)
})

第三个可能会将classes 对象包装在Proxy 中,这将在测试环境时返回键而不是值,但这似乎很笨拙,并导致组件因环境而异,我想避免这种情况.

正如我所提到的,这两种解决方案都非常受限制,因此我将不胜感激任何可以为我指明正确方向的建议/想法。

【问题讨论】:

    标签: reactjs material-ui enzyme jestjs jss


    【解决方案1】:

    我假设您正在测试孤立的组件,并且可能没有类名冲突。在这种情况下,您可以定义自己的类名生成器http://cssinjs.org/js-api?v=v9.0.0#generate-your-own-class-names,并使用简单样式的对象键作为类名。

    【讨论】:

    • 链接给出 404 未找到。
    猜你喜欢
    • 2017-02-12
    • 2020-11-02
    • 2017-04-13
    • 1970-01-01
    • 2018-08-20
    • 2021-06-24
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多