Test - sajiro/ts-love GitHub Wiki

getting container

const container = testRenderer.root.children[0] as ReactTestInstance;

TEST CODE

() => {
    const mockSelected = 'pbm';

    useStateMock.mockReturnValueOnce([selectedValueMock, jest.fn()]);

    const testRenderer = renderer.create(
      <PricingOptionGroup
        options={mockOptionGroup}
        onSelect={jest.fn()}
        selected={mockSelected}
      />
    );

    const container = testRenderer.root.findAllByType(View)[0];
    const options = container.props.children;

    options.forEach((option: ReactTestInstance, index: number) => {
      const expectedTab = mockOptionGroup[index];

      expect(option.props.title).toEqual(expectedTab.title);
      expect(option.props.subText).toEqual(expectedTab.subText);
      expect(option.props.memberPays).toEqual(expectedTab.memberPays);
      expect(option.props.value).toEqual(expectedTab.value);

      expect(option.props.testID).toEqual(`pricingOptionButton-${index}`);
    });
  }

if you are getting error on use state

//TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
//const [selectedOption, setSelectedOption] = useState(selected);
//useStateMock.mockReturnValueOnce([selectedValueMock, jest.fn()]);
 

describe('PricingOptionButton', () => {
  const onPressMock = jest.fn();
  const props = {
    title: 'Option A',
    subText: 'Some subtext',
    memberPays: 10,
    value: 1,
    onPress: onPressMock,
    isSelected: false,
    isSkeleton: false,
    testID: 'pricing-option-button',
  };

  afterEach(() => {
    jest.resetAllMocks();
  });

  it('renders correctly', () => {
    const tree = renderer.create(<PricingOptionButton {...props} />).toJSON();
    expect(tree).toMatchSnapshot();
  });

  it('calls onPress function when pressed', () => {
    const component = renderer.create(<PricingOptionButton {...props} />);
    const button = component.root.find(
      (node) => node.props.testID === 'pricing-option-button-1'
    );
    button.props.onPress();
    expect(onPressMock).toHaveBeenCalledWith(1);
  });

  it('applies active styles when isSelected is true', () => {
    const component = renderer.create(
      <PricingOptionButton {...props} isSelected={true} />
    );
    const button = component.root.find(
      (node) => node.props.testID === 'pricing-option-button-1'
    );
    expect(button.props.style).toContainEqual({
      backgroundColor: 'blue',
    });
  });

  it('applies skeleton styles when isSkeleton is true', () => {
    const component = renderer.create(
      <PricingOptionButton {...props} isSkeleton={true} />
    );
    const title = component.root.find(
      (node) => node.props.testID === 'pricing-option-button-title'
    );
    expect(title.props.style).toContainEqual({
      backgroundColor: 'lightgray',
    });
  });
});