1

I'm trying to integrate the jest to my current react project. It's a typescript project. I followed the ts-jest instructions and configured the jest. If I run simple test cases, It works well. When I add the following line or any import line the terminal gives me an error.

import React from 'react';

When I run the "npm test" command, the terminal gives me the following error. The error source is the sample test file. (test.tsx)

SyntaxError: Cannot use import statement outside a module.

I tried lots of different solutions but none of them worked.

My tsconfig.json file is;

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src",
    "global.d.ts",
    "test"
  ],
  "exclude": [
    "build",
    "coverage",
    "node_modules",
    "public"
  ]
}

babel.config.js is;

module.exports = {
    presets: ['@babel/preset-env']
}

jest.config.js is;

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    "^.+\\.(js|jsx)$": "babel-jest",
  },
  transformIgnorePatterns: ["/src/(?!serviceWorker)"],
  globals: {
    'ts-jest': {
      diagnostics: false
    }
  },
  moduleNameMapper: {
    "\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|css|less)$": "<rootDir>/src/test/resourceFileMock.ts",
  }
};

Thank you for any advice.

2
  • Hey @cinaarss, could you please add details of tsconfig.json file ? Commented Sep 28, 2021 at 18:52
  • Hi @prabhat-mishra, I added my tsconfig.json file. Thank you! Commented Sep 29, 2021 at 7:24

1 Answer 1

0

could you try with these values in your tsconfig.json:

"target": "es5",
"module": "commonjs",
"lib": ["es6"],
"jsx":"preserve",
"strict": true

Remove below values:

"module": "esnext",
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.