Search code examples
node.jstypescriptjestjstypeorm

TypeORM RepositoryNotFoundError when searching for entities using the class in Jest


I am having an issue here difficult to debug. I upgraded all my project dependencies and suddenly all my tests (Jest 25.5.4 or 26.x) started to fail with the "RepositoryNotFoundError".

The strange behavior is that all the entities are loaded in the metadata storage:

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

After some time debugging, I noticed the error is at https://github.com/typeorm/typeorm/blob/0.2.24/src/connection/Connection.ts#L482 and I created a repository for you to replicate the issue.

The comparison (metadata.target === target) always returns false. The targets are from the same class, but they are somewhat different. Using toString() return different versions of the class, one with comments stripped, another without comments (if I am using removeComments: true in my tsc config):

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

I still did not figure out what caused the issue after the upgrade. Unfortunately I cannot share the code of the project, but I can give more information if you need. Could you help me to figure out what is the problem?

My jest config (in package.json):

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

Solution

  • I still haven't tried tinkering with the example repository you provided, but I see that the paths in your TypeORM configuration files start with dist/. If you're using ts-jest and also have set src as your rootDir I think that could be the cause of your trouble.