I'm trying to run detox typescript tests in my react-native app. When an import is encountered in the test, the following error is thrown:
SyntaxError: Cannot use import statement outside a module
Details:
import { NativeModules } from 'react-native';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import axios, { AxiosInstance } from 'axios';
2 | import { isEmpty } from 'lodash';
> 3 | import VersionNumber from 'react-native-version-number';
^^^^^^
All this comes from a class I import inside the test file, which in turn imports other things that it needs.
If the test files have no imports, they work just fine.
For the past few hours I have been trying to fix this, by adjusting my jest.config.js
file but to no avail, I don't understand how this works. The solution from what I understood by googling is to use Babel to transpile the code and the imports from ES6 to commonJS, before detox/jest use them. But there are so many options in the config and the setup is not simple, I don't understand how to do it.
Below are my config files:
jest.config.js
/* eslint-disable @typescript-eslint/no-var-requires */
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('../tsconfig.json');
/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
rootDir: '..',
testMatch: ['<rootDir>/e2e/**/*.test.ts'],
testTimeout: 120000,
maxWorkers: 1,
globalSetup: 'detox/runners/jest/globalSetup',
globalTeardown: 'detox/runners/jest/globalTeardown',
reporters: ['detox/runners/jest/reporter'],
testEnvironment: 'detox/runners/jest/testEnvironment',
verbose: true,
preset: 'ts-jest',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
};
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
'@babel/preset-typescript',
['@babel/preset-env', { targets: { node: 'current' } }],
'@babel/plugin-transform-modules-commonjs',
],
plugins: [
[
'module-resolver',
{
root: ['./src'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@app': './src',
'@assets': './assets',
},
},
],
['module:react-native-dotenv', { envName: 'DOTENV', moduleName: '@env' }],
],
env: {
production: {
plugins: ['transform-remove-console'],
},
},
};
.detoxrc.js
(relevant code only)
/** @type {Detox.DetoxConfig} */
module.exports = {
testRunner: {
args: {
$0: 'jest',
config: 'e2e/jest.config.js',
},
jest: {
setupTimeout: 120000,
},
},
apps: {...},
devices: {...},
configurations: {...},
};
What I read and tried:
I would really appreciate any help or guidance.