2017-10-19 149 views
0

由於JSS組件封裝的原因,我正在用Jest測試我的React組件,並且掙扎了一番。如何使用Jest/Enzyme來測試具有JSS風格封裝的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" /> 

寫作玩笑/酶試驗,我不能使用類選擇很容易,因爲我不知道是什麼類名映射到做的時候表示。 我找到了一些解決方案,我很不高興既因爲他們是超級限制:

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

2日(不淺的工作)

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) 
}) 

3人會可能會包裝classes對象在Proxy這將返回鍵而不是價值觀,當環境測試,但似乎hacky,並導致組件的差異取決於我想避免的環境。

正如我所提到的,這兩種解決方案都非常受限制,因此我會感謝任何能夠指引我朝着正確方向的建議/ ides。

回答