首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react-native-testing-library和styled-components无法访问属性

react-native-testing-library和styled-components无法访问属性
EN

Stack Overflow用户
提问于 2021-02-05 03:23:45
回答 1查看 505关注 0票数 3

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

代码语言:javascript
复制
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- to library来访问被禁用的道具。这是我的测试:

代码语言:javascript
复制
 const { getByTestId } = render(
      <Button disabled={false} onPress={onPressMock}>
        <Text>Title</Text>
      </Button>,
    );  

但当我登录到我的测试套件时,我只看到以下内容:

代码语言:javascript
复制
  console.log(getByTestId('button.simple').props);  

在我的终端中执行console.log的结果如下:

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

我怎样才能获得通过的道具?

EN

回答 1

Stack Overflow用户

发布于 2021-02-06 02:41:58

我不确定您是否真的想访问组件的属性。检查是否通过了正确的属性,或多或少等同于测试react-native是否正确地完成了它的工作(这不是您想要测试的!但也许你有一个很好的理由...)。

如果我错了,请纠正我,但我假设你想测试的是,当你的StyledButtondisabled时,它的不透明度是否真的是0.6?如果是,我强烈建议使用testing/library/jest-native,尤其是toHaveStyle方法:

代码语言:javascript
复制
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 });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66052453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档