No entity metadata found for the specified entity within a TypeORM project when using Jest

While attempting to incorporate tests into my express/typeorm project, I encountered the following error:

            throw new error_1.EntityMetadataNotFoundError(target);
                  ^

EntityMetadataNotFoundError: No metadata for "Game" was found.
    at DataSource.getMetadata (/home/nathanfouere/Documents/AubiaChallenge/src/data-source/DataSource.ts:444:30)
    at Repository.get metadata [as metadata] (/home/nathanfouere/Documents/AubiaChallenge/src/repository/Repository.ts:53:40)
    at Repository.findOne (/home/nathanfouere/Documents/AubiaChallenge/src/repository/Repository.ts:577:42)
    at GameService.<anonymous> (/home/nathanfouere/Documents/AubiaChallenge/src/services/GameService.ts:60:61)
    at step (/home/nathanfouere/Documents/AubiaChallenge/src/services/GameService.ts:33:23)
    at Object.next (/home/nathanfouere/Documents/AubiaChallenge/src/services/GameService.ts:14:53)
    at /home/nathanfouere/Documents/AubiaChallenge/src/services/GameService.ts:8:71
    at new Promise (<anonymous>)

This is the test script:

import {GameService} from "../services/GameService";
import {aGame, aTemporarySocialClassHappinessModifier, aWorker} from "./Builders/Builders";

describe('Temporary social class modifier test', () => {
    test('adds temporary social class happiness modifier', () => {
        let duration = 4;
        let temporarySocialClassHappinessModifier = aTemporarySocialClassHappinessModifier()
            .withDuration(duration)
            .withValue(40)
            .build();
        let worker = aWorker()
            .withSocialClassHappinessModifiers([temporarySocialClassHappinessModifier])
            .build();
        let game = aGame()
            .build();
        let gameService = new GameService();
        expect(worker.socialClassHappinessModifiers).toContain(temporarySocialClassHappinessModifier);
        for (let i = 0; i < duration; i++) {
            gameService.nextTurn();
        }
        expect(worker.socialClassHappinessModifiers).toContain(temporarySocialClassHappinessModifier);
    });
});

This is the game entity structure:

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class Game {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    numberOfTurns: number
}

Here is the tsconfig.json file configuration:

{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   },
   "include": ["src/entity/Game.ts"]
}

The jest.config.js setup is as follows:

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    testMatch: ['**/src/tests/**/*.test.ts'],
};

About the data-source.ts file:

import "reflect-metadata"
import { DataSource } from "typeorm"
import {PoliticalParty} from "./entity/PoliticalParty";
import {Region} from "./entity/Map/Region";
import {Workers} from "./entity/SocialClass/SocialClass";
import {Capitalists} from "./entity/SocialClass/SocialClass";
import {MixedProperty, PrivateProperty, Property, PublicProperty} from "./entity/Property/Property";
import {Game} from "./entity/Game";
import {StateSocialClass} from "./entity/SocialClass/SocialClass";
import {State} from "./entity/State/State";
import {Product} from "./entity/Products/Product";
import {SocialClassHappinessModifier} from "./entity/HappinessModifier/SocialClassHappinessModifier/SocialClassHappinessModifier";
import {PoliticalPartyHappinessModifier} from "./entity/HappinessModifier/PoliticalPartyHappinessModifier/PoliticalPartyHappinessModifier";
import {SocialClass} from "./entity/SocialClass/SocialClass";

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "postgres",
    password: "postgres",
    database: "postgres",
    synchronize: true,
    logging: false,

    entities: [
        PoliticalParty,
        Region,
        Workers,
        Capitalists,
        Workers,
        Capitalists,
        Property,
        Game,
        StateSocialClass,
        State,
        Product,
        SocialClassHappinessModifier,
        PoliticalPartyHappinessModifier,
        SocialClass,
        PublicProperty,
        MixedProperty,
        PrivateProperty,
    ],
    migrations: [],
    subscribers: [],
})

I am facing difficulty in setting up a new database solely for testing purposes and have been unsuccessful in finding effective solutions online. Any assistance or guidance on this matter would be highly appreciated.

Answer №1

With some investigation, I discovered that the reason my test flow wasn't working was because the AppDataSource was not being initialized.

Once I included it in the beforeAll function, everything started functioning properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Class Types with Generics

Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics To make it work, I just need to call a static method before instantiation. Let's adjust the example like this: class BeeKeeper { ...

Determine the appropriate message based on the size of the array

I am encountering an issue where I have a sample document stored in a mongo atlas database: { "_id": { "$oid": "5e517a946364cc48f0ccf1e7" }, "firstName": "checkout1", "lastName": "", "companyName": "", "phoneNumber": null, ...

The object's value might be undefined, despite having null checks in place

Currently using Typescript 4.0.5 and encountering a persistent Object is possibly undefined error message My local state includes a .csv file uploaded by the user const [currentLine, setCurrentLine] = useState<File>(); The useEffect function monit ...

What is the proper way to type annotate a standard function in TypeScript?

Considering the provided type definition export interface MyFun { (arg: unknown): unknown; } It is straightforward to annotate an arrow function like this: const arrowF: MyFun = arg => { console.log(arg); } However, annotating a regular function w ...

Utilizing TypeScript: Retrieving a different class from a Promise.then() function

I am working with TypeScript and have a class called MyClass which extends Promise. The goal is for a new instance of MyClass to be returned when calling the then() method. class MyClass<I extends Arcaela.Object[] = []> extends Promise<I> { ...

Facing issues with integrating Mixpanel with NestJS as the tracking function cannot be located

While utilizing mixpanel node (yarn add mixpanel) in conjunction with NestJS, I have encountered an issue where only the init function is recognized. Despite calling this function, I am unable to invoke the track function and receive the error message: Ty ...

Issues arise with Jest tests following the implementation of the 'csv-parse/sync' library

Currently utilizing NestJs with Nx.dev for a monorepo setup. However, I've come across an issue after installing csv-parse/sync - my Jest tests are now failing to work. Jest encountered an unexpected token Jest failed to parse a file due to non-stand ...

Utilize a dual list approach while setting axios data to useState

I am encountering an issue while trying to fetch data from the backend, as one of my variable names does not conform to the naming convention. When I use setEvents(results.data.events), all fields are retrieved except for one. However, if I attempt to ma ...

Delete a particular instance of a component from an array within the parent component when a button is clicked within the child component, depending on a specific condition in Angular

One scenario I am facing involves the removal of a component instance from an array (located in the parent component) when a button is clicked inside the child component, based on a specific condition. https://i.sstatic.net/YPFHx.png Within the parent co ...

When 'Interval.after' is invoked within the library, Luxon throws an error message stating "Invalid Interval."

Encountering a strange issue with Luxon when the Interval.after method is invoked within the library. const interval = Interval.after(dateTime, duration); The following log pertains to the application DateTime__Duration, with the second line representing ...

Arranging the Node Express Application using different language paths

I am currently working on internationalizing a node expressjs-app. My plan is to host the entire website within a language-specific subfolder (www.domain.com/en/). I am finding it challenging to figure out how to structure the app, as there are limited res ...

Having trouble with the service connection in Stackblitz?

Objective: I am trying to establish a connection with the Data service in StackBlitz. Issue: Unfortunately, my attempts are not successful. Can anyone pinpoint what I am overlooking? Project Link: https://stackblitz.com/edit/angular-mpy6pr Many th ...

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

Tips for executing asynchronous functions repetitively in typescript?

Suppose I have the following setup: class Foo { constructor(obj:number) { // execute "Run" // call "Run" again after 1 second following each completion } private async Run(obj:number):Promise<void> { // includes ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Error encountered while working with SVG in a functional React component with typescript

I have a customized icon component that looks like this: import React from 'react'; type IconProps = { width?: number; height?: number; color?: string; styleName?:string; }; const MyIcon: React.FC<IconProps> = ({ width ...

Error encountered with CORS in a Socket.io Express HTTP server backend

While developing an app that utilizes express for the backend, I decided to incorporate socket.io for real-time chat functionality. Everything was working flawlessly on postman until my front end react code triggered a cors error when making a GET request ...

Angular 4 is throwing an error because it cannot find the reference to the System object

I integrated angular2-recaptcha into my project from https://github.com/xmaestro/angular2-recaptcha. Here is the snippet I added to my systemjs.config.js: System.config({ map: { 'angular2-recaptcha': 'node_modules/angular2-recaptcha& ...