What causes the distinction between entities when accessing objects through TestingModule.get() and EntityManager in NestJS?

Issue:

When using TestingModule.get() in NestJS, why do objects retrieved from getEntityManagerToken() and getRepositoryToken() refer to different entities?

Explanation:

The object obtained with getEntityManagerToken() represents an unmocked EntityManager instance. Conversely, the object obtained with getRepositoryToken() corresponds to a mocked Repository during moduleRef creation.

Sample Code:

import { Test, TestingModule } from '@nestjs/testing';
import { getEntityManagerToken, getRepositoryToken } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';

const mockEntityManager = () => ({
  query: jest.fn(),
  find: jest.fn(),
  findOne: jest.fn(),
});

describe('TEST', () => {
  let sut: Service;
  let replicaRepositoryStub: any;
  let replicateManagerStub: any;

  beforeEach(async () => {
    const moduleRef: TestingModule = await Test.createTestingModule({
      providers: [
        Service,
        {
          provide: getEntityManagerToken('replica'),
          useValue: mockEntityManager(),
        },
        {
          provide: getRepositoryToken(Entity, 'replica'),
          useValue: mockEntityManager(),
        },
      ],
    }).compile();

    sut = moduleRef.get<Service>(Service);
    replicaRepositoryStub = moduleRef.get(getRepositoryToken(Entity, 'replica'));
    replicateManagerStub = moduleRef.get(getEntityManagerToken('replica'));
  });

  it('test1', async () => {
    replicaRepositoryStub.findOne.mockResolvedValue('test'); // works fine
    replicateManagerStub.findOne.mockResolvedValue('test'); // This line triggers an error.
  });
});

Error Message:


replicateManagerStub.findOne.mockResolvedValue is not a function
TypeError: replicateManagerStub.findOne.mockResolvedValue is not a function
    at Object.<anonymous> (PATH)

Queries:

  • What causes this disparity between EntityManager and Repository instances?
  • Is there a way to acquire EntityManager via moduleRef in NestJS?
  • If so, how can it be achieved?

I have experimented with various methods to address this issue and confirmed that the object provided by moduleRef results in a fresh EntityManager instance.

Answer №1

During my situation, I included the TypeORM module while setting up a test module. This led me to believe that a fresh entity manager was generated when retrieving the entity manager from the moduleRef. Eventually, I resolved the problem by eliminating that specific section.

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 manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Issue: The --outFile flag only supports 'amd' and 'system' modules

Encountering an issue while trying to compile an Angular project in Visual Studio Code using ng build and then serving it with ng serve Unfortunately, faced the following error message in both cases: The error 'Only 'amd' and 'syste ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Why do Material UI components fail to render in jsdom while using Jest?

During my UI testing using Jest/React Testing Library, I encountered a peculiar issue. In one of my components, the return statement is structured as follows: const sidebarContentUp = ( <Drawer anchor="left" onClose={onMobileC ...

Navigating the waters of importing npm modules with typescript, gulp, and browserify is a skill

I'm facing challenges with performing some fundamental tasks such as importing packages that I installed using NPM. Despite conducting extensive research online and following various tutorials, I have been unable to achieve success. Here is my current ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

standards for matching patterns (such as .gitignore)

Throughout my experience, I have utilized various tools designed to search a codebase for specific files and then carry out operations on those files. One example is test libraries that identify all the necessary files for execution. Another common tool is ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Troubleshooting TypeScript: Issues with Object.assign and inheritance

After successfully using the code within an Angular project, I decided to switch to React only to find that the code is now producing unexpected results. class A { constructor(...parts: Partial<A>[]) { Object.assign(this, ...parts); } } cla ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

When considering Angular directives, which is more suitable for this scenario: structural or attribute?

In the process of developing an Angular 5 directive, I aim to incorporate various host views (generated from a component) into the viewContainer. However, I find myself at a crossroads as to whether I should opt for an attribute directive or a structural ...

Observable subscription does not result in updating the value

One of the challenges I'm currently facing in my Angular application is the synchronization of data from a server. To keep track of when the last synchronization took place, I have implemented a function to retrieve this information: fetchLastSyncDate ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Guide on integrating an element into a different element in a Vue 3 Tree Viewer

In my current setup, I've implemented a TreeView component that holds a tree. Each tree entry includes Children with their own unique label, perm, and further children. Take a look at an example of the tree: App.vue let tree = ref({ label: 'o ...

Setting up Firebase App Check in an Angular projectWould you like to know

I have a question about initializing Firebase app check with Angular. I am currently using AngularFire, but I'm not sure how to initialize Firebase app check before using any services. The documentation provides the following initialization code to b ...

Dismiss the Popover in Ionic 2

After opening a popover that redirects me to another page and then returning to the root page (popToRoot), I reload the data/dom upon an event and dismiss the popup once the json data is received from the server. Everything works smoothly with a lengthy ti ...