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

Are there any other methods besides @ViewChild to access template elements by template ID in Angular v4.3.3?

In the past, using @ViewChild('#templateId') was an accepted method for obtaining an Element Reference. @ViewChild('#templateId') elementName: ElementRef; However, it appears that this is no longer a viable approach as @ViewChild now ...

Unable to locate the module from my personal library in Typescript

The Query Why is my ng2-orm package not importing or being recognized by vscode when I try to import Config from 'ng2-orm'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser&a ...

Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component. The login component is located in the directory app/main/login. I am trying to navigate to the login component from app.component.html using a button. Below is the code snippet from my app-routi ...

Best approach for managing Union Types in Angular 16 Templates / Utilizing Type Inference?

Currently, I'm immersed in a project using Angular 16 where my focus lies on applying a reactive declarative method. Oftentimes, I find myself working with Observables that emit varying data types - either successful data or an error object. Each ret ...

Is it possible to use an object's attribute as a switch case in TypeScript with useReducer?

I am attempting to convert switch case String into an object, but for some reason typescript is misunderstanding the switch case within useReducer: Prior to version update, everything was functioning correctly: export const LOGIN_USER = "LOGIN_USER&qu ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

Utilizing Angular 4 to dynamically render a template stored in a string variable

Is it possible to dynamically render HTML using a string variable in Angular4? sample.component.ts let stringTemplate = "<div><p>I should be rendered as a HTML<br></p></div>"; The contents of the sample.component.html s ...

strictBindCallApply causing issues when working with generic parameters

Take a look at this slightly contrived code snippet: export function evaluate<T>(this: { value: T }) { return this.value; } class SomeClass { value: ''; constructor() { const result = evaluate.call(this); } } You might notice ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...

NextJS is currently unable to identify and interpret TypeScript files

I am looking to build my website using TypeScript instead of JavaScript. I followed the NextJS official guide for installing TS from scratch, but when I execute npm run dev, a 404 Error page greets me. Okay, below is my tsconfig.json: { "compilerOption ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...

A guide on incorporating Google authentication into Vue.js with the use of TypeScript and the component-based syntax

Currently, I am in the process of integrating Google authentication into my Vue.js front end. The project was initialized using CLI with TypeScript and component style syntax enabled, alongside other configurations. Additionally, there is a backend web ser ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

The variable is accessed prior to being assigned with the use of the hasOwnProperty method

Continuing my journey from JavaScript to TypeScript, I find myself faced with a code that used to function perfectly but is now causing issues. Despite searching for alternative solutions or different approaches, I am unable to resolve the problem. Snippe ...

Discovering a DOM Element Post Mouse Click Event Using HostListener in Angular 8

Is there a way to locate the current DOM element on a page after clicking the mouse? I am currently attempting to utilize HostListener in Angular 8. @HostListener('click') onClick(){ window.alert('Current DOM element is'); } ...

Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this: onStatusUpdateClick() { this.activatedRoute.queryPar ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...