The error message "TypeError: this.subQuery is not a function" is displayed

Whenever I execute the tests using jest, I consistently encounter the error message

TypeError: this.subQuery is not a function
pointing to a specific line in the testModelDb.test.ts file.

In the tests/jest.setup.ts file:

import 'reflect-metadata';
import dotenv from 'dotenv';
dotenv.config({ path: './.env.test' });

The contents of .env.test are as follows:

TYPEORM_CONNECTION=sqlite
TYPEORM_DATABASE=:memory:
TYPEORM_SYNCHRONIZE=true
TYPEORM_LOGGING=false
TYPEORM_ENTITIES=dist/models/**/*.js,modules/**/entity/*.ts
TYPEORM_MIGRATIONS=dist/services/db/seeding.js
TYPEORM_MIGRATIONS_RUN=true

Defined in src/models/test.model.ts:

@Entity()
export default class TestModel {
    @PrimaryGeneratedColumn()
    id!: number;

    @Column()
    name!: string;

    @OneToMany(() => OtherModel, (other) => other.testModel)
    otherModels!: OtherModel[];
}

And finally, in the tests/testModelDb.test.ts file:

describe('Integrationtests', () => {
    let connection: Connection;

    beforeAll(async () => { connection = await createConnection(); });

    afterAll(() => connection?.close());

    beforeEach(async () => { await connection.synchronize(true); });

    describe(`functions`, () => {
        describe(`#function1()`, () => {
            test('Test 1', async () => {
                await connection
                    .createQueryBuilder()
                    .insert()
                    .into(TestModel) // <- here
                    .values([ {name: 'Test item 1'} ])
                    .execute();
              
                expect(true).toBe(true);
                
            });
        });
    });
});

Answer №1

When setting up the connection, double-check that you have included the entity name within the entities:[] configuration property.

Answer №2

Encountered an issue that required removing a redundant datasource instance of Typeorm in the code, here's how I resolved it:

Below is my ormconfig setup:

import 'dotenv/config'
import { DataSource } from "typeorm"
import { Users, Wallet } from "../entities"

const datasource = new DataSource({
    type: "postgres",
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT),
    database: process.env.DB_DATABASE,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    entities: [Users, Wallet],
    migrations: [__dirname + "/migrations/*{.js,.ts}"],
})

datasource.initialize();

export default datasource;

However, there was an oversight in how I implemented this script in my code.

import { Wallet } from '../entities';
import { DataSource } from 'typeorm'
import { IWalletRepository } from '../interfaces/wallet-repository'
import datasource from '../config/ormconfig'; // <---I imported my ormconfig 

export class WalletRepository implements IWalletRepository{
  AppDataSource: DataSource // <-- but I didn't passed here
  async get (userId: Wallet['user_id']): Promise<Wallet> {
    return this.AppDataSource
    .getRepository(Wallet)
    .createQueryBuilder('wallet')
...

The solution was simply to pass my ormconfig to AppDataSource

  AppDataSource: DataSource = datasource

Hopefully, this explanation proves helpful!

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

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Incorrect Angular Routing Component OpeningI am experiencing an issue where

I am facing an issue with lazy loading a module, where it is not correctly displaying the desired component. Even though the route seems correct, it shows a different component instead. Despite specifying the path for "Push-Campaign", it displays the "Cli ...

I seem to be stuck in an endless cycle with React hooks and I can't figure out the root cause

Explore the example here: https://codesandbox.io/s/wandering-wildflower-764w4 Essentially, my goal is to achieve the following: In the provided example, I have a server validation function that has been mocked. My objective is to maintain the state local ...

In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a compone ...

What is the best method for testing an npm package that has been delivered as a .tgz file in a React

I have a npm package that is in .tgz file format included in my react application. When I try to test a react component using jest that imports this package, I encounter the following error. Do I need to configure something in jest for testing? Jest e ...

What is the best approach to handle Flow types for component props and getDerivedStateFromProps when the props are not the same

Having a Component with its props, an additional prop is added for getDerivedStateFromProps. The issue arises when setting the props with the additional one, throwing an error that the prop is not being used. Conversely, setting it without the extra prop c ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

What strategies can I use to steer clear of the pyramid of doom when using chains in fp-ts?

There are times when I encounter a scenario where I must perform multiple operations in sequence. If each operation relies solely on data from the previous step, then it's simple with something like pipe(startingData, TE.chain(op1), TE.chain(op2), TE. ...

Is TypeScript declaration merging not functioning properly?

Trying to enhance an existing interface with a new member is causing Typescript errors for me. // foo.js export interface IOption { xOffset: number } import {IOption} from 'foo'; // Attempting to extend IOption with `yOffset`, but encounter ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

The type '[Images]' cannot be assigned to type 'string'

I am attempting to pass an array of objects through props, but encountered the following error: (property) images: [Images] Type '[Images]' is not assignable to type 'string'.ts(2322) ProductBlock.tsx(4, 5): The expected type co ...

Tips for dynamically accessing object properties in TypeScript

I've been going through the process of converting existing Node.js projects to TypeScript. As part of this, I am utilizing the http-status package (https://www.npmjs.com/package/http-status) for handling HTTP status codes. While trying to pass varia ...

Issue: Angular 7 unable to route directly to URL with specific ID

When I click on the navigation link with code for button click, it works perfectly fine: this.router.navigate(['/dashboard', this.selectedDateString]); However, if I manually type the URL into the address bar like this: I receive a forbidden! ...

What is the reason behind taps in TypeScript only registering the first tap event?

One issue I am encountering is that only the first tap works when clicked, and subsequent taps result in an error message: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') Here is the code I am using: https://codepen ...

An error occurs with webpack during postinstall when trying to load TypeScript

I have created a custom package that includes a postinstall webpack script as specified in my package.json file: "scripts": { ... "postinstall": "webpack" } The webpack configuration looks like this: const path = require('path'); ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...