2017-05-31 128 views
0

我有一个问题关于用酶测试,所以基本上我在做什么的东西,看起来像:测试风格的成分与酶

const BaseButton = styled.button` 
    padding: 10px; 
`; 

const PrimaryButton = BaseButton.extend` 
    color: red; 
`; 

const SecondaryButton = BaseButton.extend` 
    color: blue; 
`; 

// My actual component: 
const buttonTypes = { 
    primary: PrimaryButton, 
    secondary: SecondaryButton 
}; 
export const Button = (props: Props) => { 
    const { type = 'primary' } = props; 
    const Btn = buttonTypes[type] || buttonTypes.primary; 

    return (
     <Btn 
      {...props} 
      onClick={props.onClick} 
     > 
      {props.children} 
     </Btn> 
    ); 
}; 

我想要做一些测试与酶在经过不同的道具type,例如测试应该这样说:

should render a Primary button if type='primary'

should render a Secondary button if type='secondary'

should render a Primary button if type=''

should render a Primary button by default

我的按钮有办法更多的​​属性,但我只是表现为color简单起见。

关于如何实现这一点的任何想法?

回答

-1

我最终什么事做的是:

  1. 添加数据属性按钮
  2. 安装使用酶
  3. 安装我以前component.html()获得组件作为一个字符串后,组件
  4. 检查是否应用了正确的属性
// Button.js 
const buttons = { 
    primary: 'primary', 
    secondary: 'secondary' 
}; 

export const ButtonStyles = styled.button.attrs({ 
    'data-button-type': props => buttons[props.type] || buttons.primary 
})` 
    padding: 10px; 
`; 

// Button.tests.js 

it('should render a primary button when type prop is missing',() => { 
    const wrapper = mount(
     <Button 
      {...defaultProps} 
      type="" 
     /> 
    ); 

    expect(wrapper.html().includes('data-button-type="primary"')).toBeTruthy(); 
});