【问题标题】:react-native-testing-library and styled-components can't access propsreact-native-testing-library 和 styled-components 无法访问道具
【发布时间】:2021-05-09 03:45:18
【问题描述】:

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

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'

如何访问传递的道具?

【问题讨论】:

  • 你到底想测试什么?
  • @aquinq。我正在尝试测试我的组件是否包含在其道具中:“已禁用”

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


【解决方案1】:

我不确定您是否真的想要访问组件的 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 });
});

【讨论】:

  • @aquiq 对于这个用例你是对的 ;) 但奇怪的是即使我做了一个 expect(queryByTestId ('buttonID'))。 toHaveProp ('disabled') 或我拥有的任何其他道具 null
猜你喜欢
  • 2021-07-13
  • 2019-10-07
  • 2022-09-25
  • 2019-08-06
  • 2018-03-06
  • 2020-01-08
  • 2020-08-03
  • 1970-01-01
  • 2020-03-05
相关资源
最近更新 更多