简体   繁体   中英

Jest encountered an unexpected token when importing lodash functions in Typescript

I am getting an error: Jest encountered an unexpected token when trying to compile in my test classes on lines:

import isEqual from 'lodash-es/isEqual';
import isEmpty from 'lodash-es/isEmpty';

In my package.json I setup my dependency like this:

  "dependencies": {
    "lodash-es": "^4.17.11"
  },
  "devDependencies": {
     ...
     "@types/jest": "^23.3.13",
     "@types/node": "^11.13.4",
     "@types/lodash-es": "^4.17.3",
     "jest": "^25.2.4",
     "ts-jest": "^23.10.4",
     "tslint": "^5.14.0",
     "typescript": "^3.6.4"
     ...
  }

I set my jest config like this:

module.exports = {
    clearMocks: true,
    collectCoverageFrom: ['<rootDir>/src/**/*.+(ts)'],
    coverageDirectory: 'coverage',
    coveragePathIgnorePatterns: [
        '/test/',
        '/dist/',
        '<rootDir>/src/index.ts',
        '<rootDir>/src/imports.ts'
    ],
    coverageThreshold: {
        global: {
            branches: 100,
            functions: 100,
            lines: 100,
            statements: 100,
        },
    },
    moduleFileExtensions: ['ts', 'js', 'json', 'node'],
    preset: "ts-jest/presets/js-with-ts",
    rootDir: '.',
    testEnvironment: 'node',
    testMatch: ['<rootDir>/test/**/*.test.(js|ts)'],
    transform: {
        '\\.(js|ts)$': '<rootDir>/node_modules/babel-jest'
    },
    transformIgnorePatterns: [
        "node_modules/(?!(lodash-es)/)"
    ]
  };

As suggested by other posts I've tried adding in transform, and transformIgnorePatterns. I've also tried with jest --no-cache, and removing node_modules, package-lock.json, and then rebuilding with tsc, and using NodeJS 12. Yet, I still get the same error. Is there something I am misconfiguring?

My jest configuration had a couple mistakes:

    transform: {
            '\\.(js|ts)$': 'ts-jest',
    },

I also needed to update the preset to: preset: 'ts-jest', . I was mixing and matching configuration from different sources which was causing weird compile errors. Updating the configuration fixed my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM