【问题标题】:TypeORM RepositoryNotFoundError when searching for entities using the class in Jest使用 Jest 中的类搜索实体时出现 TypeORM RepositoryNotFoundError
【发布时间】:2020-08-29 01:11:10
【问题描述】:

我在这里遇到了一个难以调试的问题。我升级了所有项目依赖项,突然我的所有测试(Jest 25.5.4 或 26.x)都开始失败,并出现“RepositoryNotFoundError”。

奇怪的行为是所有实体都加载到元数据存储中:

import { Connection, getMetadataArgsStorage } from 'typeorm';
let connection = await createConnection(); //<- The connection is creating according to my config

console.log(getMetadataArgsStorage()); //<- All the entities are here
console.log(getRepository('User')); //<- This works
console.log(getRepository(User)); //<- But this will raise the error

经过一段时间的调试,我注意到错误在https://github.com/typeorm/typeorm/blob/0.2.24/src/connection/Connection.ts#L482,我创建了a repository for you to replicate the issue

比较 (metadata.target === target) 总是返回 false。目标来自同一类,但它们有些不同。使用 toString() 返回该类的不同版本,一个带有 cmets 剥离,另一个没有 cmets(如果我在我的 tsc 配置中使用 removeComments: true):

const targetMetadata = connection.entityMetadatas[7].target; // 7 is the index in my debug, it can be anything else in the array

console.log(targetMetadata === User); // prints false

我仍然没有弄清楚升级后导致问题的原因。不幸的是,我无法分享该项目的代码,但如果您需要,我可以提供更多信息。你能帮我找出问题所在吗?

我的笑话配置(在 package.json 中):

"jest": {
  "moduleFileExtensions": [
    "js",
    "json",
    "ts"
  ],
  "rootDir": "src",
  "testRegex": ".spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "coverageDirectory": "../coverage",
  "testEnvironment": "node"
}

【问题讨论】:

    标签: node.js typescript jestjs typeorm


    【解决方案1】:

    我还没有尝试修改您提供的示例存储库,但我看到您的 TypeORM 配置文件中的路径以 dist/ 开头。如果您使用的是ts-jest 并且还设置了src 作为您的rootDir,我认为这可能是您遇到问题的原因。

    【讨论】:

    • 我认为你是对的。我将在本周晚些时候进行更多测试,以确保在更改路径(迁移、实体...)后一切正常。
    • 感谢您的提示。我太专注于其他事情,以至于完全忘记了那个配置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多