【问题标题】:When runing tests in jest, node_modules imports gets undefined在玩笑中运行测试时,node_modules 导入未定义
【发布时间】:2022-12-05 18:58:33
【问题描述】:

我的玩笑配置有什么问题,我无法在玩笑执行中解决node_modules?他们变得不确定......

示例测试文件:

import lodash from 'lodash'

it('test', () => {
  expect(lodash.max([1,2])).toBe(2)
})

测试(笑话)输出:

Cannot read properties of undefined (reading 'max')
TypeError: Cannot read properties of undefined (reading 'max')

开玩笑.config.js:

/** @type {import('ts-jest').JestConfigWithTsJest} */
const tsconfig = require('./tsconfig.json')
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig)

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleNameMapper,
}

webpack.config.js:

const path = require('path')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin').default
const nodeExternals = require('webpack-node-externals')

module.exports = {
  entry: './src/server.ts',
  target: 'node',
  externals: [nodeExternals()],
  devtool: 'source-map',
  mode: process.env.RUNTIME_ENV === 'production' ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.(ts|js)$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.(graphql|gql)$/,
        loader: '@graphql-tools/webpack-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    plugins: [new TsconfigPathsPlugin({})],
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
}

tsconfig.json:

{
  "compilerOptions": {
    "lib": ["ESNext"],
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES2020",
    "outDir": "lib",
    "isolatedModules": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "allowJs": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*.ts","./global.d.ts"],
  "exclude": [
    "node_modules/**/*",
    "_warmup/**/*",
    ".vscode/**/*"
  ]
}

【问题讨论】:

    标签: javascript node.js typescript jestjs ts-jest


    【解决方案1】:

    在我的例子中,问题在于导入 CommonJS/AMD/UMD 模块。我的 tsconfig.json 中缺少 "esModuleInterop": true

    这个题目对我有帮助:https://github.com/vercel/ms/issues/186

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 2019-01-07
      • 2018-06-02
      • 2017-11-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2018-11-14
      相关资源
      最近更新 更多