1

我试图阅读 at testing-library/react-native的文档,并在 stackoverflow 上进行了搜索,但没有找到好的结果。

我有这个组件

import React from 'react';
import { CardContainer, Title, Icon, Item, ClickableItem, StyledRow, StyledRowImage } from './style';

interface Props {
  title?: string;
  imageURL?: any;
  onPress?: () => {};
  children?: JSX.Element;
  iconWidth?: number;
  iconHeight?: number;
  padding?: number;
  withouIcon?: boolean;
  setBorder?: {};
  fontSize?: number;
  margin?: number;
  withoutIcon?: boolean;
}
const ClickableCard: React.FC<Props> = ({
  title,
  imageURL,
  onPress,
  children,
  iconWidth,
  iconHeight,
  padding,
  setBorder,
  fontSize,
  setMargin,
  withoutIcon,
  expand = false,
}) => {
  return (
    <CardContainer
      padding={padding}
      style={expand !== true ? { display: 'flex', flexShrink: 0.5, flexGrow: 0.5 } : null}
    >
      {children || (
        <ClickableItem onPress={onPress} setBorder={setBorder} setMargin={setMargin}>
          <>
            {!withoutIcon && (
              <StyledRowImage>
                {imageURL && <Icon source={imageURL} iconWidth={iconWidth} iconHeight={iconHeight} />}
              </StyledRowImage>
            )}
            <StyledRow>
              <Title fontSize={fontSize}>{title}</Title>
            </StyledRow>
          </>
        </ClickableItem>
      )}
    </CardContainer>
  );
}

我需要测试第一个padding收到数字的道具。我也试过 getByText 但是,obv,它不起作用。

我尝试过了


import React from 'react';
import { fireEvent, render, wait } from '@testing-library/react-native';
import ClickableCard from '@components/ClickableCard';

describe('ClickableCard component', () => {
  it('renders correctly', () => {
    render(<ClickableCard />);
  });

  it('renders with the specified padding', () => {
    const { queryBy } = render(<ClickableCard padding={10} />);

    const padding = queryBy(10);
    expect(padding).toBeDefined();
    expect(padding.children.length).toBe(10);
    expect(padding.children[0]).toBe('ClickableCard');
  });
});

我问自己是否存在某种 getByNumber 或类似的东西。

问题是:

我怎样才能正确测试const { queryBy } = render(<ClickableCard padding={10} />);

4

1 回答 1

0

参考:react-native-testing-io

it('renders with the specified padding', () => {
  const { getByTestId } = render(<ClickableCard testID="card" padding={10} />)
  const card = getByTestId('card') 
  expect(card.props.padding).toBe(10)
})

上面只测试了 props,所以如果你添加一个snapshotthis 将显示填充是否实际应用在组件的样式中。

it('renders with the specified padding', () => {
  const element = render(<ClickableCard testID="card" padding={10} />)
  const card = element.getByTestId('card') 

  expect(card.props.padding).toBe(10)
  expect(element.toJSON()).toMatchSnapshot()
})
于 2020-10-12T14:31:41.377 回答