How do I fix SyntaxError: Cannot use import statement outside a module using Jest?

How do I fix SyntaxError: Cannot use import statement outside a module using Jest?

我几乎尝试了每一个教程和方法来让 Jest 识别导入语句。但是,我无法在 2021 年找到可行的解决方案。

我尝试过的事情:

这是我当前的布局。我也试过很多其他的。

错误信息:

  
    /Users/lukeanglin/Desktop/Convene/frontend/convene/node_modules/expo-secure-store/build/SecureStore.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { UnavailabilityError } from 'expo-modules-core';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { LOGIN_URL } from '../config/globals';
      2 | import { LOG } from '../config/logger-conf';
    > 3 | import * as SecureStore from 'expo-secure-store';
        | ^
      4 | import axios from 'axios';
      5 | export async function login(email, password) {
      6 |   // Returns true if login succeeds and false on fail (also logs error message)
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { LOGIN_URL } from '../config/globals';
      2 | import { LOG } from '../config/logger-conf';
    > 3 | import { SecureStore } from 'expo-secure-store';
        | ^

babel.config.json

{
    "presets": ["@babel/preset-env"]
}

package.json

// stuff here 
"type": "module",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "lint": "eslint .",
    "lint:fix": "eslint --fix",
    "format": "prettier --write './**/*.{js,jsx,ts,tsx,css,md,json}' --config ./.prettierrc",
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\.[t|j]sx?$": "babel-jest"
    }
},
// stuff here

重现步骤:

此外,导致导入错误的文件的全部内容在这里:

login.js

import { LOGIN_URL } from '../config/globals';
import { LOG } from '../config/logger-conf';
import * as SecureStore from 'expo-secure-store';
import axios from 'axios';
export async function login(email, password) {
  // Returns true if login succeeds and false on fail (also logs error message)
  try {
    const response = await axios.post(LOGIN_URL, {
      username: email,
      password: password
    });
    // Save the token
    const token = response['data']['token']
    await SecureStore.setItemAsync('token', token);
    return true;
  } catch (error) {
    LOG.error(
      'Error on GET request to login for authentication OR error on storing token with SecureStore: \n' +
        error
    );
    return false;
  }
}

并且测试测试函数 login

任何具有 Jest 和 Babel 的工作配置以使 SecureStore 等 ES6 模块具有功能性(以及导入语句、导出等)的人可以帮助我,我将非常感谢你!

TLDR - 如何使用 Jest 修复 SyntaxError: Cannot use import statement outside a module

最终,我了解到这不是 Babel 或 Jest 配置的问题,而是仅限于 SecureStore 项目本身.这个模块似乎特别提出问题,因为其他导入工作。