繁体   English   中英

react-native-testing-library 和 styled-components 无法访问道具

[英]react-native-testing-library and styled-components can't access props

我有一个这样定义的样式组件:

export const StyledButton = styled.TouchableOpacity<IButtonProps>
  height: 46px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 46px;
  border-radius: 8px;
  background: ${EAppColors.BLACK};
  opacity: ${props => (props.disabled ? 0.6 : 1)};
;

interface IButtonProps {
  readonly children: React.ReactNode;
  readonly onPress: () => any;
  readonly style?: StyleProp<ViewStyle>;
  readonly testID?: string;
  readonly disabled?: boolean;
}

const Button: React.FC<IButtonProps> = ({
  children,
  style,
  onPress,
  disabled = false,
}) => {
  return (
    <StyledButton
      testID={'button.simple'}
      onPress={onPress}
      style={style}
      disabled={disabled}>
      {children}
    </StyledButton>
  );
};

我想用 react-native-testing-library 访问禁用的道具。 有我的测试:

 const { getByTestId } = render(
      <Button disabled={false} onPress={onPressMock}>
        <Text>Title</Text>
      </Button>,
    );  

但是当我登录我的测试套件时,我只有这个:

  console.log(getByTestId('button.simple').props);  

我的终端中 console.log 的结果:

  {
    accessible: true,
    style: {
      height: 46,
      width: '100%',
      display: 'flex',
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      borderRadius: 8,
      backgroundColor: '#000000',
      opacity: 1
    },
    testID: 'button.simple'

如何访问传递的道具?

我不确定您是否真的想访问组件的 prop。 检查是否通过了正确的道具,或多或少等同于测试react-native是否正确完成其工作(这不是您想要测试的。但也许您有充分的理由......)。

如果我错了,请纠正我,但我假设您要测试的是StyledButton的不透明度在disabled时是否确实为0.6 如果是,我强烈推荐使用testing/library/jest-native ,尤其是toHaveStyle方法:

it('sets the correct opacity if disabled', () => {
  const { getByTestId } = render(
    <Button disabled={true} onPress={onPressMock}>
      <Text>Title</Text>
    </Button>
  );

  const button = getByTestId('button.simple');

  expect(button).toHaveStyle({ opacity: 0.6 });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM