I am testing some React-Native components. For context, my components are stored in the following manner:
project
-components
--componentA
---ComponentA.js
---__test__
----ComponentA.test.js
--componentB
---ComponentB.js
---__test__
----ComponentB.test.js
--componentC
---ComponentC.js
---__test__
----ComponentC.test.js
The components have import statements, like the following:
import React from 'react';
import { Text, TouchableOpacity, View, StyleSheet} from 'react-native';
Components A and Components B rendered successfully and passed their respective tests. Component C is unable to have its test suite start due to the error SyntaxError: Cannot use import statement outside a module. The imports for Component C are as follows:
import React from 'react';
import Constants from 'expo-constants';
import { View, Text, StyleSheet, TouchableOpacity, Image, ScrollView } from 'react-native';
import { COLORS } from '../../styles/COLORS';
import BackButton from '../widgets/BackButton';
import backImage from '../../../assets/navigation/leftArrow.png';
import { SECTIONS } from './consts';
import setStatusBarColor from '../utils/StatusBarColorFunctions';
The error pointed at line 2, where Constants is imported. I commented out the line and ran the test again, and then pointed out the import statement for View, Text, etc., particularly at TouchableOpacity. I read some other posts that adding "type":"module" to the package.json file could resolve the issue, but I did not have issues with the two other components undergoing similar tests. If I change the file to require statements instead of import statements, it resolves the issue, but import statements are used for the other files and my tests run successfully. Is there a reason why this file in particular would have issues compared to the others, when they are are in the same directories?
Also I am fairly new to this site so if other information is needed from me please let me know. Thanks in advance!
Update: I am experiencing this with other files as well. If anyone has suggestions, please let me know!
all you need is a propterty at yow package.json
{
"name": "project",
"version": "1.0.0",
....
"type": "module",
....
}
add the type module property into your package or if you are using babel make sure the first line of code read is
request("@babel/register");