0

I wondering how can I test this kind of code with react native testing library?

const Component = () => (
  <View style={styles.iconWrapper}>
    {Platform.select({
      ios: (
        <Icon
          name="arrow-back-ios"
          size={ICON_SIZE}
          color={BaseColors.primary}
          testID="ios-back-icon"
        />
      ),
      android: (
        <Icon
          name="arrow-back"
          size={ICON_SIZE}
          color={BaseColors.black}
          testID="android-back-icon"
        />
      ),
    })}
  </View>
);

I try this but doesn't work.

1 Answer 1

0

Add this mock to your jest.config as per the link you refer to:

jest.mock('react-native/Libraries/Utilities/Platform', () => {
  let platform = {
    OS: 'ios',
  }

  const select = jest.fn().mockImplementation((obj) => {
    const value = obj[platform.OS]
    return !value ? obj.default : value
  })

  platform.select = select

  return platform
});

I simplified your example code a bit, cause I don't have all those variables:

const Component = () => (
  <View>
    {Platform.select({
      ios: <Text testID="ios-back-icon"> Hi </Text>,
      android: <Text testID="android-back-icon"> Hi </Text>,
    })}
  </View>
);
export default Component;

import React from 'react';
import {render} from '@testing-library/react-native';
import Component from './App';
import {Platform} from 'react-native';

describe('Component', () => {
  it('ios should render correctly', () => {
    Platform.OS = 'ios';
    let {queryByTestId} = render(<Component />);
    expect(queryByTestId('ios-back-icon')).not.toBeNull();
    expect(queryByTestId('android-back-icon')).toBeNull();
  });
  it('android should render correctly', () => {
    Platform.OS = 'android';
    let {queryByTestId} = render(<Component />);
    expect(queryByTestId('android-back-icon')).not.toBeNull();
    expect(queryByTestId('ios-back-icon')).toBeNull();
  });
});

I tested this and it works on my machine. If it doesn't work for you, let me know. There are probably some issues with your configuration. Make sure to use queryByTestId and not get, that can't handle it if it cannot find what it is looking for (so you cannot test with 'not')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.