Ways to imitate typeORM repository

Looking for some guidance on writing tests and mocking the typeORM repository. I've tried a few approaches, but couldn't quite figure it out, particularly with the @InjectRepository method. Any suggestions?

import { AfterRoutesInit, Service } from '@tsed/common';
import { TypeORMService } from '@tsed/typeorm';
import { Connection, Repository } from 'typeorm';
import { DbAccount } from '../entity/DbAccount';
import { DbAddress } from '../entity/DbAddress';
import { Account } from '../models/Account';
import { Address } from '../models/address';
import { Pageable } from '../models/api_common/Pageable';

@Service()
export default class AccountService implements AfterRoutesInit {
    private repository: Repository<DbAccount>;
    private addressRepository: Repository<DbAddress>;

    constructor(private typeORMService: TypeORMService) { }

    $afterRoutesInit(): void | Promise<any> {
        const connection: Connection = this.typeORMService.get('default');
        this.repository = connection.getRepository(DbAccount);
        this.addressRepository = connection.getRepository(DbAddress);
    }

    async delete(accountId: string): Promise<void> {
        await this.repository.delete(accountId);

        return;
    }

}

Answer №1

Just in case your problem has not been resolved yet, here is a solution:

import {TestContext} from "@tsed/testing";
import {TypeORMService} from "@tsed/typeorm";
import {expect} from "chai";
import * as Sinon from "sinon";
import {AccountService} from "./AccountService";
import {DbAccount} from "./DbAccount";
import {DbAddress} from "./DbAddress";

describe("AccountService", () => {
  before(() => TestContext.create());
  after(() => TestContext.reset());
  describe("afterRoutesInit()", () => {
    it("should initialize repository when afterRoutesInit event is emitted", () => {
      // GIVEN
      const connection = {
        getRepository: Sinon.stub()
      };
      const typeORMService = {
        get: Sinon.stub().returns(connection)
      };
      const dbAccountRepository = {name: "dbAccountRepository"};
      const dbAddressRepository = {name: "dbAddressRepository"};

      connection.getRepository
        .withArgs(DbAccount).returns(dbAccountRepository);
      connection.getRepository
        .withArgs(DbAddress).returns(dbAddressRepository);

      const service = TestContext.invoke<AccountService>(AccountService, [
        {
          provide: TypeORMService,
          use: typeORMService
        }
      ]);

      // WHEN
      service.$afterRoutesInit();

      // THEN
      expect(typeORMService.get).to.have.been.calledWithExactly("default");
      expect(service.repository).to.deep.eq(dbAccountRepository);
      expect(service.addressRepository).to.deep.eq(dbAddressRepository);
    });
  });
});

Note: I utilized chai and sinon for writing unit tests :)

Answer №2

This is my preferred approach.

import chai from 'chai';
import {UserService, User} from 'myApp';

describe('User service Unit tests:', () => {
   const expect = chai.expect;
   
   beforeEach(() => {
    // Set up test environment
   })

   afterEach(() => {
     // Clean up after each test
   })

   it('register() creates a new user successfully', (done) => {
      // Test logic for user registration 
   }) 
})

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

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

core.js:12853 Error encountered when trying to use 'ngIf' on a 'div' element that is not recognized as a valid property

I am currently utilizing Angular 9. and I am faced with a scenario where I need to load dynamic components Within one of my components, I encountered the following warning core.js:12853 Can't bind to 'ngIf' since it isn't a known pro ...

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

How can variables from state be imported into a TypeScript file?

Utilizing vue.js along with vuetify, I have a boolean value stored in state via Vuex defined in src/store/index.ts (named darkMode). This value is used within one of my view components inside a .vue file. However, I now wish to access the same variable in ...

Angular service unit test failed to execute

I have a service that I need to test, so I created a file named 'maincause.service.spec.ts' as shown below: fdescribe('MainCauseService', () => { let injector: TestBed; let service: MainCauseService; let httpMock: HttpTestin ...

Utilizing the power of Typescript in Express 4.x

I'm currently working on building an express app using TypeScript and here is what my code looks like at the moment: //<reference path="./server/types/node.d.ts"/> //<reference path="./server/types/express.d.ts"/> import express = requir ...

Issue: Module './App' not found in webpackSolution: Check if the module path is

I've decided to switch my .js files to .tsx in order to start using TypeScript. To incorporate TypeScript, I used the following command: yarn add typescript @types/node @types/react @types/react-dom @types/jest and began converting first index.tsx fo ...

Guide to making type-safe web service requests using Typescript

When utilizing Angular for web service calls, it's important to note that the type of the returned object is not automatically verified. For example, let's say I have a Typescript class named Course: export class Course { constructor( publ ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

Incorporating the Chartist plugin into an Angular 5 application

Currently, I am facing an issue while attempting to create a project in Angular 5 that involves utilizing chartist @types and js files of chartist plugins. Interestingly, the files compile without any issues in Angular 4, but encounter difficulties when t ...

Using TypeScript to define attributes by merging specified attribute names with variable attribute names

Can a TypeScript type/interface be created with the specified structure below? interface Model { id: number; something: string; somethingElse: Date; [key: string]: string | null; } It essentially consists of both defined attributes and 0 to n und ...

Using TypeScript with Selenium

What are the benefits of utilizing Selenium with Typescript in comparison to Selenium with Java? In what ways can Selenium+Typescript automate certain types of web applications that Selenium+Java cannot, and why is this the case? ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

Step-by-step guide on filtering an array of objects using Vuejs and TypeScript

For this particular project, I am utilizing Vuejs Typescript with a data structure that looks like this: ["order": { "id":1, "created_at":"2019-12-06T10:22:17Z", "status":"open", ...

The functionality of Angular's mat-autocomplete is hindered when it comes to utilizing options generated by a function

I decided to enhance the autocomplete feature on my project by taking an example from the Material official website. Instead of having the options stored in a variable within the component class, I created a function to retrieve the options. Although the o ...

Add information to an array by simply modifying the existing data that shares the same key/value pair

Currently, I am working on the front-end of a delivery web application. On one of the screens, I have implemented a Google map that allows the company owner to track their delivery riders in real-time. The process of implementing the map itself was quite s ...

Encountered an issue with retrieving schema during self-referencing validation with openapi generator

I created an openapi specification and now I am looking to generate a client for it. openapi.yaml After some research, I decided to use the openapi generator to create a typescript-axios client. This is the command I used: openapi-generator-cli generate ...

"Encountered a problem when trying to access properties within a

Struggling to access properties of a nested object in TypeScript while using Angular, I encountered the following error: Object is possibly 'undefined'. Here is the code snippet: export interface Address{ city?: string; neighborhood?: string; } ...