Troubleshooting 'Connection "default" was not found' error while mocking getManager in NestJS service unit testing

Currently undergoing unit testing for my NestJS Service with an entity named 'User'. I have created a simple Service to interact with a MS SQL server, setting up GET and POST endpoints in the Controller.

One of the service methods I am focusing on mocking is the deleteV2 function, as shown below:


// service file 
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { Connection, createConnection, EntityManager, getConnection, getManager, getRepository, Repository } from "typeorm";
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository<User>,
              @InjectConnection() private connection: Connection,
              @InjectEntityManager() private manager: EntityManager
              ) {}

  async delete(id: number): Promise<any> {
    return await this.manager.delete(User, id);
  }

  async deleteV2(id: number): Promise<any> {
    return await getManager().delete(User, id);
  }

Importing EntityManager and injecting a manager: EntityManager into my service is for practicing different methods as a new intern working with NestJS. The unique use of defining both delete and deleteV2 methods serves a purpose in unit testing with varied approaches. Repository, Connection, and EntityManager injection further contribute to this practice.

In my spec.ts unit testing file for the service, I have:

// unit testing file for the service

type MockType<T> = { 
    [P in keyof T]?: jest.Mock<{}>;
};

describe('service tests', () => {
    const mockManagerFactory = jest.fn(() => ({
        delete: jest.fn().mockReturnValue(undefined),
    }))
 
    let service: ServiceName;
    let mockManager: MockType<EntityManager>; 

    beforeEach(async () => {     
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                {
                    provide: getEntityManagerToken(),
                    useFactory: mockManagerFactory,
                },
            ],
        }).compile();

        service = module.get<ServiceName>(ServiceName);
        mockManager = module.get(getEntityManagerToken());
    });
})

Within the same spec.ts file, multiple tests are defined. The one concerning deleteV2 is causing issues. The error message encountered is:

● service tests › Service Functions › second test

ConnectionNotFoundError: Connection "default" was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getManager (index.ts:260:35)

Seeking advice on how to resolve this error, specifically related to handling the imported getManager method in comparison to the injected manager within the service.

Answer №1

One of the major advantages of utilizing dependency injection is highlighted here. Instead of having to worry about setting up connections manually, @InjectEntityManager() simply injects the object with the connection already established, allowing you to focus on using the methods without any connection-related concerns. This approach greatly simplifies testing, in my personal opinion. Conversely, employing getManager() necessitates navigating TypeORM's process of retrieving the entity manager from the active connection, which can be problematic during testing scenarios. To address this, you can create a mock using something similar to the following snippet using jest:

const deleteMock = jest.fn();
jest.mock('typeorm', () => ({
  getManager: () => ({
    delete: deleteMock,
  })
}))

While the above method works fine, it is advisable to refrain from directly calling functions like getConnection and getManager from TypeORM whenever possible.

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

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

Type inference error in TypeScript occurs within a conditional statement when the condition relies on the output of a function call rather than a boolean expression

In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list. type ListItem = number | string | object; class Node { private value: ListItem; private next: Node | nu ...

Sending input in a nested event listener

I am currently utilizing Highcharts for the purpose of showcasing an interactive map with custom countries. I have a specific requirement to enable the drilldown functionality, which involves clicking on a country to zoom in on another map displaying inter ...

Ensuring typescript req.user in Passport JS is always defined: Best practices

When utilizing Passport JS, the req.user within the route is considered potentially undefined. However, the middleware prior to my route method ensures that this scenario does not occur. How can I convey this information to TypeScript? Object may be &apos ...

Winston's createLogger function is not defined

After setting up Jest unit tests in a TypeScript Node project, I encountered an issue where the main code broke after installing Jest with ts-node. Whenever I try to run npm test or npm start, I receive the following error: [nodemon] watching extensions: t ...

Showing the outcome of the request from the backend on an HTML page using the MEAN stack

I am currently in the process of developing an angular application with a node.js + express backend. After successfully retrieving the necessary data from MongoDB and being able to view it through terminal, I encountered a challenge when trying to display ...

Preserve Inference in Typescript Generics When Typing Objects

When utilizing a generic type with default arguments, an issue arises where the inference benefit is lost if the variable is declared with the generic type. Consider the following types: type Attributes = Record<string, any>; type Model<TAttribu ...

Utilize Function type while preserving generics

Is there a way in Typescript to reference a function type with generics without instantiating them, but rather passing them to be instantiated when the function is called? For instance, consider the following type: type FetchPageData<T> = (client : ...

Utilizing Router Outlet in Angular to Access API Data

I've encountered an issue where I can't pass parent data from the ngOnInit route params to my child component, user-seminar. After some research and searching on Google, I found a solution involving services. To address this problem, I modified ...

Error: Attempting to access 'update' property of a null value

function logUserOut(user: UserInstance) { return user.update({ token: null }); } I encountered an error at this part of the code. Any suggestions on how to fix it? ...

Setting property values in Typescript by initializing them from other properties when reading objects from a subscription response

I have created a basic class structure export class SampleObj{ item1: string; item2: string; item3: string; } I am fetching data from the backend and populating this class using HttpClient: this.httpClient.get<SampleObj[]>(`backendUrl`).subscr ...

What is the best way to make the SPA load with the tab displaying the highest value?

I have a React single-page application using Typescript and Material UI. One challenge I'm facing is creating a tab menu with the current month and all previous months, where the last month should be active when the page loads. Despite researching on ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Tips for resolving the unmounted component issue in React hooks

Any suggestions on resolving this issue: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect ...

Is it possible to utilize an angular 1 template in conjunction with angular 2?

I am currently working on developing a real-time reactive admin dashboard for a Dashboard/POS system. While I primarily work with Java and have experience with .net, I have recently started practicing with the MEAN stack for creating real-time web applicat ...

Can a NestController access the NestApplication instance?

I have these two files: main.ts async function initializeApp() { const application = await NestFactory.create(AppModule); application.enableCors(); application.setGlobalPrefix('api'); application.useGlobalPipes(new ValidationPipe()); a ...