jest-mongodb 和 Typescript - 加载预设时出错

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

好像无法加载预设

文件:jest.config.js

 preset: "@shelf/jest-mongodb",

问题总结

  • 问题出在 global.__MONGO_URI__ 上,它返回 undefined。
  • 运行测试命令(package.json):“test”:“jest --passWithNoTests”,
  • 在窗口上运行
  • 使用 GitBash
  • 安装成功后,执行时会生成globalConfig.json文件,其中包含uri和dbname。

enter image description here

错误

enter image description here

error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no 

安装

jest-mongodb-config.js

module.exports = {
  mongodbMemoryServerOptions: {
    instance: {
      dbName: 'jest',
    },
    binary: {
      version: '4.0.3',
      skipMD5: true,
    },
    autoStart: false,
  },
};

jest.config.js

module.exports = {
  roots: ["<rootDir>/src", "<rootDir>/tests"],
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
  ],
  testEnvironment: 'node',
  preset: "@shelf/jest-mongodb",
  coverageDirectory: "coverage",
  testEnvironment: "node",
  transform: {
    ".+\\.ts$": "ts-jest",
  },
  moduleNameMapper: {
    '@/tests/(.*)': '<rootDir>/tests/$1',
    '@/(.*)': '<rootDir>/src/$1'
  },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.ts$", 
};

用法

  beforeAll(async () => {
    client = await MongoClient.connect(global.__MONGO_URI__, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    } as ConnectOptions)
    db = client.db()
  })

我已经尝试过:

  1. 重新安装jest-mongodb
  2. 按照文档创建一个新项目
  3. 重新加载、关闭并重新打开 vscode
  4. 使用 process.env。MONGO_URL
  5. 安装:
 npm --save-dev @shelf/jest-mongodb
 yarn add @shelf/jest-mongodb --dev
typescript mongodb jestjs
1个回答
0
投票

解决了! 我从 process.env 获取内容并找到 MONGO_URL。 所以我改变了:

global.__MONGO_URI__

process.env.MONGO_URL

请勿与下划线一起使用!不行的

process.env.__MONGO_URL__
© www.soinside.com 2019 - 2024. All rights reserved.