Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test platform specific extension code for React Native

Currently, React Native dynamically requires a file for the running platform with an specific file extension, *.ios.js or *.android.js. However, when running this code inside a test environment, we get a require error because the module require('./module') cannot be found in the file tree, which looks like:

  • module.ios.js
  • module.android.js

How can we handle this issues in a test environment?

like image 476
amb Avatar asked Apr 07 '16 14:04

amb


People also ask

How we can write the platform specific code in react native?

Note: Platform specific code can also be written by making use of the Platform module from react-native. import React, { Component } from 'react'; import { TextInput, View } from 'react-native'; import PropTypes from 'prop-types'; import styles from './TextArea.

How do you detect the platform on which app is running in react native?

React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.

What is the file extension for react native?

The react-native mode is the equivalent of preserve in that it keeps all JSX, but the output will instead have a . js file extension.

What platforms support react native?

React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows and UWP by enabling developers to use the React framework along with native platform capabilities.


2 Answers

Adding platform specific extensions to moduleFileExtensions fixed the problem for me with jest.14.1. Credits to : github link

Here is a snippet from sample package.json which will run all files including scene.jest.js(x).

...
"jest": {
    "verbose": true,
    "preset": "jest-react-native",
    "moduleFileExtensions": ["js", "android.js", "ios.js"],
    "testRegex": "\\.scene\\.jest\\.jsx$"
  }
 ...
like image 80
cubbuk Avatar answered Oct 01 '22 01:10

cubbuk


As of Jest 17.0.0 you can use the defaultPlatform configuration for this - see the very bottom of the Jest React Native tutorial.

As it shows there, you would configure something like this:

"haste": {
  "defaultPlatform": "ios",
  "platforms": ["android", "ios"],
},

Naturally, this will mean your tests only load the iOS version of your component (or only Android, depending how you choose to configure it).

If you find it important to test both versions, you'll probably need to do something more like the solution mentioned in this issue, possibly manipulating Platform.OS and using require.requireActual directly.

(Might also want to track this issue, in case a less hacky solution is eventually found.)

like image 39
Tomty Avatar answered Oct 01 '22 02:10

Tomty