Skip to content

Instantly share code, notes, and snippets.

@dtsolis
Created September 23, 2020 14:51
Show Gist options
  • Save dtsolis/792c0d8a16ab3981d9db5ae781eb28b7 to your computer and use it in GitHub Desktop.
Save dtsolis/792c0d8a16ab3981d9db5ae781eb28b7 to your computer and use it in GitHub Desktop.
// @flow
import { Platform } from 'react-native';
let _accessibilityWorkaround = Platform.OS === 'android';
let _enabled = process.env.NODE_ENV === 'test';
/**
* Whether or not the for where end-to-end test frameworks (like Appium) cannot
* find components having `testID` property.
* Default is `true` on Android but `false` on every other platform.
*
* @returns {boolean} `true` if the workaround is enabled. Otherwise, `false`.
*/
export const isAccessibilityWorkaroundEnabled = (): boolean =>
_accessibilityWorkaround;
/**
* Enables/disables the workaround for Android (or other platforms if needed),
* where end-to-end test frameworks (like Appium) cannot find components having
* `testID` property.
* The workaround is to set the `accessibilityLabel` property.
*
* NOTE: Although this is OK or testing, it is NOT ok for production.
* Accessibility features should be used for accessibility purposes.
* Shipping this to production will result bad UX for your end-users that
* actualy need the accessibility features.
*
* @param {boolean} enabled `true` if the workaround should be enabled. Otherwise, `false`.
*/
export const setAccessibililtyWorkaroundEnabled = (enabled: boolean) => {
_accessibilityWorkaround = Boolean(enabled);
};
export const isEnabled = (): boolean => _enabled;
export const setEnabled = (enabled: boolean) => (_enabled = Boolean(enabled));
/**
* Used to locate a specific view in end-to-end tests.
*
* Recommended to use it after setting the accessibility properties
* like the example below:
*
* @example
* ```
* <BottomTabBar
* accessible={true}
* accessibilityLabel={"Bottom Tab Bar"}
* {...testID('bottom-tabbar')}
* />
* ```
*
* @param {string} test_id The testID to use for locating "this view" in end-to-end tests.
* @returns {{
* testID?: string,
* accessible?: boolean,
* accessibilityLabel?: string,
* }} The component properties you need for testing.
*/
const testID = (
test_id: string,
): {
testID?: string,
accessible?: boolean,
accessibilityLabel?: string,
} => {
if (!_enabled) {
return {};
}
const accessibilityProps = {};
if (_accessibilityWorkaround) {
accessibilityProps.accessible = false;
accessibilityProps.accessibilityLabel = test_id;
}
return {
testID: test_id,
...accessibilityProps,
};
};
export default testID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment