使用 jest 测试 .ts 文件

问题描述 投票:0回答:1

我正在使用 jest 来测试我的 TypeScript 代码,但 jest 无法识别从我的代码导入的依赖项(“lodash-es”)。

这是错误消息:

  ● 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:

    C:\Users\Sunrise\sunrise\karman\node_modules\lodash-es\lodash.js:10
    export { default as add } from './add.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | import { ClassSignature } from "@/types/common.type";
      2 | import { ParameterDescriptor } from "@/types/rules.type";
    > 3 | import { isUndefined, isNull, isString } from "lodash-es";
        | ^
      4 |
      5 | const existValue = (value: unknown) => !isUndefined(value) && !isNull(value);
      6 |

这是我的笑话配置的一部分:

module.exports = {
  preset: "ts-jest",
  transform: {
    "^.+\\.js$": "babel-jest",
  },
  transformIgnorePatterns: [],
}

I've been asking ChatGPT and read the jest doc for all day, but still can't solve this problem...
unit-testing testing lodash ts-jest babel-jest
1个回答
0
投票

尝试将其添加到您的 jest.preset.js 中:

module.exports = {
  collectCoverage: true,
  moduleNameMapper: {
    '^lodash-es$': 'lodash',
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.