Set up a unique database in memory for every individual test

Is it feasible to create an in-memory database for each test scenario?

My current approach involves using the code snippet below, which functions properly when running one test file or utilizing the --run-in-band option.

import _useDb from "@/useDb";
import { mocked } from "ts-jest/utils";
import { createConnection, getConnection } from "typeorm";

const useDb = mocked(_useDb);

jest.mock("@/useDb");

beforeEach(async () => {
  useDb.mockImplementation(async (action) => {
    const db = await createConnection({
      type: "sqlite",
      database: ":memory:",
      dropSchema: true,
      entities: [Entity],
      synchronize: true,
      logging: false,
    });

    await action(db);
  });
});

afterEach(async () => {
  const con = getConnection();

  await con.close();
});

However, running multiple tests simultaneously triggers the following error:

CannotExecuteNotConnectedError: Cannot execute operation on "default" connection because connection is not yet established.

I am aware of a suggestion in this Stack Overflow post to include a name attribute with a random uuid. But I wonder if there is an alternative method to instruct TypeORM not to index connections by name. Is there a parameter that can achieve this functionality?

Answer №1

I managed to get it working successfully, although I'm not exactly sure how. Maybe this information will be helpful for someone in the future. Here is my setup for beforeEach and afterEach:

beforeEach(async () => {
  const con = await createConnection({
    type: "sqlite",
    database: ":memory:",
    dropSchema: true,
    entities: [],
    synchronize: true,
    logging: false,
  });

  mockGetDbConnection.mockResolvedValue(con);
});

afterEach(async () => {
  const con = getConnection();

  await con.close();
});

mockGetDbConnection is the function used to obtain a DB handle for services. If you do not have that, you can simply use getConnection provided by TypeORM.

In addition, I have included this in jest as setupFilesAfterEnv and it seems to be functioning perfectly.

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

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

"Enhancing user experience with MaterialUI Rating feature combined with TextField bordered outline for effortless input

I'm currently working on developing a custom Rating component that features a border with a label similar to the outlined border of a TextField. I came across some helpful insights in this and this questions, which suggest using a TextField along with ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

Utilize forRoot to pass configuration data

When using Angular, I encountered a challenge in passing configuration data to a custom library. Within the user's application, they are required to provide config data to my library through the forRoot method: // Importing the custom library import ...

Encountering a compilation error when implementing ActionReducerMap in combination with StoreModule.forFeature

In my Angular project, the structure is organized as follows: /(root or repo folder) |_ projects |_ mylib (main library to be exported from the repo) |_ sample-app (created for testing 'mylib' project in other projects) To manage appli ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

Encountering an issue with a MEAN application using Angular 2: The error message states "Cannot read property

As a first-time application developer, I am working on creating a system to manage Client profiles. Utilizing the Angular tour of heroes for the basic structure, I integrated mongodb and express components sourced from various online platforms. However, I ...

Transfer dynamically generated table data to the following page

Seeking guidance on a common issue I'm facing. I am creating a table using data from Firebase upon page load, and I want users to click on a row to view specific details of that item. It may sound confusing, but it will make more sense with the code p ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

The value of req.headers('Authorization') has not been defined

I'm experiencing difficulty with my code as the token is coming back as undefined. Here is the frontend section: export const fetchUser = async (token: any) => { const res = await axios.post('/user/getuser', { headers ...

Angular UI validation malfunctioning upon loading of the page

My webpage contains multiple rows with specific validation requirements - at least one Key, Time, and Input must be selected. Initially, the validation works as expected. However, after saving and reloading the page, the default selection for Key, Time, an ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

How can we implement `injectReducer` in Redux with TypeScript?

I have been working on a TypeScript React application with Redux to manage state. To dynamically add reducers, Redux suggested implementing an injectReducer function. In a JavaScript project, I successfully implemented this function. However, I am strugg ...

Utilize the array map function in a React Native functional component with useState to dynamically render content

I have successfully implemented a functional component that renders a basic form with input elements. My goal is to allow users to dynamically add input elements by clicking a button. To achieve this, I am utilizing the useState hook and have created an o ...

How can I reduce unnecessary spacing in a primeNg Dropdown (p-dropdown) filter within an Angular 5 application?

In my Angular 5 project, I have implemented PrimeNG dropdown (p-dropdown) and encountered an issue. When I try to filter the dropdown data by adding spaces before and after the search term, it displays a No Results Found message. How can I fix this problem ...

Using React and TypeScript to create multiple click handlers for different sections within the same div element

I am a beginner in the world of React, Typescript, and coding in general, so I'm not entirely sure if what I'm attempting is even possible. Currently, I have a donut chart with clickable segments sourced from a minimal pie chart found at: https:/ ...