Short Version
I'm experiencing a crash in my Jest test due to a SyntaxError related to an import statement outside a module. The issue arises from a node_module that uses the import statement. How can I resolve this error?
Situation Overview
In developing a Next.js app, I have Jest as my testing framework and employ Magic for authentication purposes. To run my Jest tests in TypeScript, I utilize ts-node.
The specific challenge lies in testing a serverless function that incorporates the @magic-sdk/admin package, which depends on the ethereum-cryptography library for its keccak hash algorithm.
During test execution, it crashes because of the import statement within the ethereum-cryptography package.
FAIL src/features/user-authentication/login-handler.test.ts
● Test suite failed to run
Jest encountered an unexpected token
...
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.292 s
Ran all test suites related to changed files.
My tsconfig.json configuration is as follows:
{
"compilerOptions": {
...
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
This is how my jest config file (jest.config.ts) looks like:
export default {
moduleDirectories: ['node_modules', 'src'],
moduleNameMapper: {
'\\.(css|less)$': '<rootDir>/src/tests/mocks/style-mock.js',
},
setupFilesAfterEnv: ['./jest.setup.ts'],
setupFiles: ['<rootDir>/src/tests/setup-environment-variables.js'],
};
Attempted Solutions
Despite finding numerous search results for this common error, none of the suggested fixes have worked so far. Here's what I've attempted:
- Including the folder in transformIgnorePatterns did not yield the desired outcome.
- Explicit transformation using transform and ts-jest was also ineffective.
- Changing the module to commonjs in the tsconfig.json file did not address the issue either.
How can I troubleshoot this and successfully execute the test case?