Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JEST: SyntaxError: Unexpected token 'export' #11435

Closed
3 tasks done
therealkh opened this issue May 31, 2023 · 14 comments
Closed
3 tasks done

JEST: SyntaxError: Unexpected token 'export' #11435

therealkh opened this issue May 31, 2023 · 14 comments
Assignees
Labels
Core Related to core Amplify issues investigating This issue is being investigated React Native React Native related issue

Comments

@therealkh
Copy link

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

Authentication

Amplify Categories

auth

Environment information

# Put output below this line
System:
    OS: macOS 13.3.1
    CPU: (8) arm64 Apple M1 Pro
    Memory: 45.88 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.16.0 - ~/.nvm/versions/node/v18.16.0/bin/node
    Yarn: 3.5.1 - ~/.nvm/versions/node/v18.16.0/bin/yarn
    npm: 9.5.1 - ~/.nvm/versions/node/v18.16.0/bin/npm
    Watchman: 2023.05.15.00 - /opt/homebrew/bin/watchman
  Browsers:
    Chrome: 113.0.5672.126
    Safari: 16.4
  npmPackages:
    @apollo/client: ^3.7.14 => 3.7.15 
    @apollo/client/cache:  undefined ()
    @apollo/client/core:  undefined ()
    @apollo/client/errors:  undefined ()
    @apollo/client/link/batch:  undefined ()
    @apollo/client/link/batch-http:  undefined ()
    @apollo/client/link/context:  undefined ()
    @apollo/client/link/core:  undefined ()
    @apollo/client/link/error:  undefined ()
    @apollo/client/link/http:  undefined ()
    @apollo/client/link/persisted-queries:  undefined ()
    @apollo/client/link/retry:  undefined ()
    @apollo/client/link/schema:  undefined ()
    @apollo/client/link/subscriptions:  undefined ()
    @apollo/client/link/utils:  undefined ()
    @apollo/client/link/ws:  undefined ()
    @apollo/client/react:  undefined ()
    @apollo/client/react/components:  undefined ()
    @apollo/client/react/context:  undefined ()
    @apollo/client/react/hoc:  undefined ()
    @apollo/client/react/hooks:  undefined ()
    @apollo/client/react/parser:  undefined ()
    @apollo/client/react/ssr:  undefined ()
    @apollo/client/testing:  undefined ()
    @apollo/client/testing/core:  undefined ()
    @apollo/client/utilities:  undefined ()
    @apollo/client/utilities/globals:  undefined ()
    @babel/core: ^7.20.0 => 7.22.1 
    @babel/preset-env: ^7.20.0 => 7.22.4 
    @babel/runtime: ^7.20.0 => 7.22.3 
    @graphql-codegen/cli: ^2.13.12 => 2.16.5 
    @graphql-codegen/typescript: ^2.8.2 => 2.8.8 
    @graphql-codegen/typescript-operations: ^2.5.7 => 2.5.13 
    @graphql-codegen/typescript-react-apollo: ^3.3.6 => 3.3.7 
    @react-native-async-storage/async-storage: ^1.18.1 => 1.18.1 
    @react-native-community/eslint-config: ^3.2.0 => 3.2.0 
    @react-native-community/netinfo: ^9.3.10 => 9.3.10 
    @react-native-masked-view/masked-view: ^0.2.9 => 0.2.9 
    @react-navigation/elements: ^1.3.17 => 1.3.17 
    @react-navigation/native: ^6.1.6 => 6.1.6 
    @react-navigation/native-stack: ^6.9.12 => 6.9.12 
    @reduxjs/toolkit: ^1.9.5 => 1.9.5 
    @reduxjs/toolkit-query:  1.0.0 
    @reduxjs/toolkit-query-react:  1.0.0 
    @shopify/react-native-skia: ^0.1.192 => 0.1.193 
    @testing-library/react-native: ^12.1.2 => 12.1.2 
    @tsconfig/react-native: ^2.0.2 => 2.0.3 
    @types/jest: ^29.2.1 => 29.5.1 
    @types/lodash-es: ^4.17.7 => 4.17.7 
    @types/react: ^18.0.24 => 18.2.7 
    @types/react-test-renderer: ^18.0.0 => 18.0.0 
    HelloWorld:  0.0.1 
    amazon-cognito-identity-js: ^6.2.0 => 6.2.0 
    aws-amplify: ^5.2.4 => 5.2.4 
    babel-jest: ^29.2.1 => 29.5.0 
    babel-plugin-module-resolver: ^5.0.0 => 5.0.0 
    dependency-cruiser: ^13.0.0 => 13.0.2 
    eslint: ^8.19.0 => 8.41.0 
    eslint-plugin-functional: ^5.0.8 => 5.0.8 
    eslint-plugin-import: ^2.27.5 => 2.27.5 
    eslint-plugin-simple-import-sort: ^10.0.0 => 10.0.0 
    graphql: ^16.6.0 => 16.6.0 (15.8.0)
    jest: ^29.2.1 => 29.5.0 
    lodash-es: ^4.17.21 => 4.17.21 
    metro-react-native-babel-preset: 0.73.9 => 0.73.9 
    prettier: ^2.4.1 => 2.8.8 
    react: 18.2.0 => 18.2.0 
    react-native: 0.71.8 => 0.71.8 
    react-native-config: ^1.5.1 => 1.5.1 
    react-native-confirmation-code-field: ^7.3.1 => 7.3.1 
    react-native-gesture-handler: ^2.10.1 => 2.10.1 
    react-native-linear-gradient: ^2.6.2 => 2.6.2 
    react-native-reanimated: ^3.1.0 => 3.2.0 
    react-native-render-html: ^6.3.4 => 6.3.4 
    react-native-safe-area-context: ^4.5.3 => 4.5.3 
    react-native-screens: ^3.20.0 => 3.20.0 
    react-native-svg: ^13.9.0 => 13.9.0 
    react-redux: ^8.0.5 => 8.0.7 
    react-test-renderer: 18.2.0 => 18.2.0 
    redux: ^4.2.1 => 4.2.1 
    redux-saga: ^1.2.3 => 1.2.3 
    redux-saga-test-plan: ^4.0.6 => 4.0.6 
    redux-saga/effects:  undefined ()
    ts-node: ^10.9.1 => 10.9.1 
    typed-redux-saga: ^1.5.0 => 1.5.0 ()
    typescript: 4.8.4 => 4.8.4 
  npmGlobalPackages:
    @aws-amplify/cli: 12.0.3
    corepack: 0.17.0
    npm: 9.5.1


Describe the bug

Jest tests are throwing error in line where I import Auth from aws-amplify.
Screenshot 2023-05-31 at 15 12 44

Expected behavior

Test shouldn't be failed.

Reproduction steps

Jest configuration:

const libsThatRequiredCompilation = [
  '@react-navigation/elements',
  '@react-native-community/netinfo',
  'lodash-es',
].join('|');

export default {
  preset: 'react-native',
  clearMocks: true,
  automock: false,
  setupFiles: ['./jest-mock.ts'],
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    `node_modules/(?!((jest-)?react-native|${libsThatRequiredCompilation}|@react-native(-community)?)/)`,
  ],
  globalSetup: './jest-setup.js',
  testPathIgnorePatterns: ['/node_modules/', '/e2e/'],
  testMatch: ['**/?(*.)+(spec|test).(j|t)s?(x)'],
  collectCoverageFrom: [
    './src/**/*.ts',
    '!./src/app/store/sagas/rootSaga.ts',
    '!./src/**/use*.ts',
    '!./src/**/index.ts',
    '!./src/**/apiTypes.ts',
    '!./src/app/store/store.ts',//TODO: cover store with tests
    '!./src/shared/navigation/defaultScreenOptions.ts',
    '!./src/shared/gradients/gradients.ts'
  ],
  coverageThreshold: {
    './src/**/*.ts': {
      branches: 85,
      functions: 85,
      lines: 85,
      statements: -10,
    },
  },
  reporters: ['default'],
};

Babel config:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        extensions: ['.js', '.ts', '.tsx', '.json'],
        alias: {
          '~': ['./src'],
        },
      },
    ],
    'react-native-reanimated/plugin',// has to be listed last
  ],
};

Code Snippet

import { Auth } from 'aws-amplify';
import { call, put, SagaGenerator } from 'typed-redux-saga';

import { signUp, signUpResponse } from '~/entities/auth';

export function* signUpSaga({
  payload,
}: ReturnType<typeof signUp>): SagaGenerator<void> | Promise<Response> {
  try {
    const { email, password, phoneNumber } = payload;
    const response = yield* call([Auth, 'signUp'], {
      username: email,
      password,
      attributes: {
        phone_number: phoneNumber,
      },
    });

    yield put(signUpResponse({ data: response }));
  } catch (error) {}
}
import { Auth } from 'aws-amplify';
import { expectSaga } from 'redux-saga-test-plan';
import * as matchers from 'redux-saga-test-plan/matchers';

import { signUp, signUpResponse } from '~/entities/auth';

import { signUpSaga } from './signUpSaga';
// Replace with the actual path to your module file
const mockPayload = {
  email: '[email protected]',
  password: 'password123',
  phoneNumber: '1234567890',
};
const mockResponse = {
  user: {
    username: '[email protected]',
    pool: {
      userPoolId: 'us-east-1_XXXXXXX',
      clientId: 'XXX',
      client: {
        endpoint: 'https://cognito-idp.us-east-1.amazonaws.com/',
        fetchOptions: {},
      },
      advancedSecurityDataCollectionFlag: true,
    },
    Session: null,
    client: {
      endpoint: 'https://cognito-idp.us-east-1.amazonaws.com/',
      fetchOptions: {},
    },
    signInUserSession: null,
    authenticationFlowType: 'USER_SRP_AUTH',
    keyPrefix: 'CognitoIdentityServiceProvider.XXXXXXX',
    userDataKey:
      'CognitoIdentityServiceProvider.XXXXXXX.text@example.ioqqq.userData',
  },
  userConfirmed: false,
  userSub: 'XXXXX-XXXX-XXXX-XXXX-XXXX',
  codeDeliveryDetails: {
    AttributeName: 'email',
    DeliveryMedium: 'EMAIL',
    Destination: 't***@e***',
  },
};

describe('signUpSaga', () => {
  it('handle signUpSaga with CORRECT parameters', () => {
    return expectSaga(signUpSaga, signUp(mockPayload))
      .provide([[matchers.call.fn(Auth.signUp), true]])
      .put(signUpResponse({ data: mockResponse }))
      .run();
  });
});

Log output

// Put your logs below this line


aws-exports.js

const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_identity_pool_id": "us-east-1:XXXX-XXXX-XXXX-XXXX-XXXXX",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_XXXX",
    "aws_user_pools_web_client_id": "XXXXXXX",
    "oauth": {},
    "aws_cognito_username_attributes": [
        "EMAIL"
    ],
    "aws_cognito_social_providers": [],
    "aws_cognito_signup_attributes": [
        "EMAIL",
        "PHONE_NUMBER"
    ],
    "aws_cognito_mfa_configuration": "OFF",
    "aws_cognito_mfa_types": [
        "SMS"
    ],
    "aws_cognito_password_protection_settings": {
        "passwordPolicyMinLength": 10,
        "passwordPolicyCharacters": [
            "REQUIRES_LOWERCASE",
            "REQUIRES_UPPERCASE"
        ]
    },
    "aws_cognito_verification_mechanisms": [
        "EMAIL"
    ]
};


export default awsmobile;

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

@therealkh therealkh added the pending-triage Issue is pending triage label May 31, 2023
@nadetastic nadetastic added Auth Related to Auth components/category Core Related to core Amplify issues React Native React Native related issue labels May 31, 2023
@cwomack cwomack self-assigned this May 31, 2023
@cwomack cwomack added investigating This issue is being investigated and removed pending-triage Issue is pending triage labels May 31, 2023
@cwomack
Copy link
Member

cwomack commented Jun 1, 2023

Hello @therealkh, and thanks for opening this issue. I'm curious if we can resolve this by making a change to your transformIgnorePatterns since I believe Jest won't transform the node_modules by default. I'm referencing this comment from the Jest GitHub repo, but can you try updating it similar to this:

"transformIgnorePatterns": [
  // Change MODULE_NAME_HERE to your module that isn't being compiled
  "/node_modules/(?!MODULE_NAME_HERE).+\\.js$"
]

@cwomack cwomack added pending-response and removed Auth Related to Auth components/category labels Jun 5, 2023
@cwomack
Copy link
Member

cwomack commented Jun 6, 2023

@therealkh, it looks like this issue should also be resolved with PR #11422 actually. Can you update your dependency and verify?

@cwomack
Copy link
Member

cwomack commented Jun 6, 2023

Closing this issue as we have not heard back from you. If you are still experiencing this, please review the above comments regarding resolutions/fixes and feel free to reply back and we'd be happy to re-open the issue.

Thank you!

@cwomack cwomack closed this as completed Jun 6, 2023
@luisfuertes
Copy link

@cwomack i have same problem

i test your solution

    "transformIgnorePatterns": [
      "/node_modules/(?!aws-amplify).+\\.js$"
    ]

and have this error on all test, with amplify and without amplify import

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

I have installed "aws-amplify": "^5.2.5" version

@cwomack
Copy link
Member

cwomack commented Jun 26, 2023

@luisfuertes, you'd need to update your transformIgnorePatterns to be the specific module that's giving you an error. Are you getting the exact same error/module as described in this issue or a different one?

The Jest docs may offer a better example and explanation of how to configure the array for transformIgnorePatterns, but reply back if it's still giving you issues.

@Pixcell
Copy link

Pixcell commented Jun 29, 2023

Hello,
I'm currently migrating from CRA to vite, and I encounter the same error.

  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /<PATH_TO_PROJECT>/node_modules/@aws-sdk/client-lex-runtime-service/node_modules/uuid/dist/esm-browser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

    > 1 | import { Auth } from 'aws-amplify';
        | ^
      2 |
      3 | export const currentUser = async () => {
      4 |   return Auth.currentAuthenticatedUser();

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/node_modules/@aws-sdk/middleware-retry/dist-cjs/StandardRetryStrategy.js:6:16)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/node_modules/@aws-sdk/middleware-retry/dist-cjs/AdaptiveRetryStrategy.js:6:33)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/node_modules/@aws-sdk/middleware-retry/dist-cjs/index.js:4:22)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/dist-cjs/LexRuntimeServiceClient.js:9:28)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/dist-cjs/LexRuntimeService.js:9:35)
      at Object.<anonymous> (node_modules/@aws-sdk/client-lex-runtime-service/dist-cjs/index.js:5:22)
      at Object.<anonymous> (node_modules/@aws-amplify/interactions/src/Providers/AWSLexProvider.ts:10:1)
      at Object.<anonymous> (node_modules/@aws-amplify/interactions/src/Providers/index.ts:3:1)
      at Object.<anonymous> (node_modules/@aws-amplify/interactions/src/Interactions.ts:11:1)
      at Object.<anonymous> (node_modules/@aws-amplify/interactions/src/index.ts:4:1)
      at Object.require (node_modules/aws-amplify/src/index.ts:25:1)
      at Object.require (src/helpers/auth.js:1:1)
      at Object.require (src/helpers/tokenProvider.js:4:1)
      at Object.require (src/api/api-helpers.js:1:1)
      at Object.require (src/api/bff-api.js:2:1)
      at Object.require (src/api/__test__/bff-api.test.js:1:1)

Babel config is the following

     module.exports = {
       presets: ['@babel/preset-env', '@babel/preset-react'],
       plugins: ['babel-plugin-transform-import-meta', '@babel/plugin-transform-modules-commonjs']
     };

jest is configured in the package.json

     
  "jest": {
    "globalSetup": "<rootDir>/globalSetup.js",
    "setupFilesAfterEnv": [
      "@testing-library/jest-dom/extend-expect"
    ],
    "testEnvironment": "jsdom",
    "snapshotSerializers": [
      "jest-serializer-html"
    ],
    "transformIgnorePatterns": [
      "/node_modules/(?!aws-amplify|@aws-sdk/client-lex-runtime-service/node_modules/@aws-sdk/middleware-retry).+\\.js$"
    ],
    "moduleNameMapper": {
      "^konva": "konva/konva",
      "\\.(css|scss|less)$": "identity-obj-proxy"
    },
    "resetMocks": false
  },

As you can see, I tried to add the transformIgnorePatterns, but to no effect.

Any help would be greatly appreciated @cwomack

@git-sparrow
Copy link

Using transformIgnorePatterns did not work in my case.

I've replaced the import from this:
import { Auth } from 'aws-amplify';
To this:
import Auth from "@aws-amplify/auth";

Not sure whether this is the optimal solution but it works for me.
After this, the Jest error disappeared.

I'm using "aws-amplify": "5.2.0"

@Pixcell
Copy link

Pixcell commented Jul 2, 2023

@git-sparrow That helps solving the issues with the Auth import, but the same issue arise for

   <PATH>/node_modules/@aws-sdk/client-lex-runtime-service/node_modules/uuid/dist/esm-browser/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 | import { NavigateNext as NavigateNextIcon } from '@mui/icons-material';
       6 | import { makeStyles } from '@mui/styles';
    >  7 | import { useAuthenticator } from '@aws-amplify/ui-react';
    ```
    
    And I can't find a suitable replacement import

@Pixcell
Copy link

Pixcell commented Jul 3, 2023

Turns out, this time adding


    "transformIgnorePatterns": [
      "<rootDir>/node_modules/(?!(@aws-amplify\/ui-react))/"
    ],

Did the trick.
Although this considerably slows down test execution time.
Exposing the heapusage of tests also explodes.
It goes over 2.5/2.8 GB per test, even forcing garbage collection after each test https://plazagonzalo.medium.com/how-to-solve-memory-leak-problems-on-node-js-while-running-jest-a33839d49bb1

@superflav
Copy link

FWIW, what ended up working for me was adding a moduleNameMapper line to my jest.config.js file as detailed here: https://stackoverflow.com/a/73203803

// jest.config.js
{
//................
  moduleNameMapper: {
    // Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
    "uuid": require.resolve('uuid'),
  }
}

@steveharrison
Copy link

The moduleNameMapper and transformIgnorePatterns solutions both solved the issue for me, also each one slowing the tests down like the authors mentioned. However, I have just upgraded to AWS Amplify 6, and everything seems to work now without the hacks. Only thing I had to update was to import the Hub from the new path: import { Hub } from 'aws-amplify/utils'; And no slowness with this solution!

@lausek
Copy link

lausek commented Apr 4, 2024

@superflav That works for me but only after moving moduleNameMapper to my jest project settings. It's not picking up the root level configuration.

{
  // does nothing
  moduleNameMapper: { ... },
  projects: [
    {
      // this works
      moduleNameMapper: { ... }
    }
  ]
}

@rizbud
Copy link

rizbud commented May 13, 2024

it works for me by adding this to jest.setup.js

jest.mock("aws-amplify", () => ({
  Auth: jest.fn()
}))

@anabeatrizzz
Copy link

anabeatrizzz commented Jan 13, 2025

This solved the issue for me

package.json

"jest": {
  // ...
  "moduleNameMapper": {
    "^uuid$": "uuid"
  }
}

Reference

@github-actions github-actions bot added the pending-maintainer-response Issue is pending a response from the Amplify team. label Jan 13, 2025
@AllanZhengYP AllanZhengYP removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Jan 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Core Related to core Amplify issues investigating This issue is being investigated React Native React Native related issue
Projects
None yet
Development

No branches or pull requests