javascript - react-native-testing-library 和 styled-components 无法访问 Prop

标签 javascript react-native jestjs styled-components react-testing-library

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

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 来访问禁用的 Prop 。 这是我的测试:

 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 ?

最佳答案

我不确定您真的想要访问组件的 prop。 检查是否传递了正确的 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 });
});

关于javascript - react-native-testing-library 和 styled-components 无法访问 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66052453/

相关文章:

javascript - div限制字符的文本,添加 "Read more"链接,点击链接显示所有字符

javascript - Web组件快照测试

react-native - React Native Webview如何使用injectJavascript

javascript - react-native - 当获取结束时调用另一个函数

javascript - 使用 fetch 检查图像是否存在(函数不返回响应)

javascript - 开 Jest - watch 模式错误

javascript - 如何正确模拟节点模块以进行 Jest 单元测试

javascript - jqGrid 显示 'edit' 图标用于行内编辑

javascript - 如何让 Raphael Canvas 全屏显示?

javascript - 当我用 jquery 将鼠标悬停在图像上时,如何使跨度保持不变?