Ensure that the database is properly configured before running any test suites

Currently, I am facing the challenge of seeding my database with all the necessary resources required to successfully test my API. These tests are spread across multiple files.

Is there a method that will allow me to fully seed the database before any test from any suite is executed?

I am hoping to accomplish this without relying on beforeAll and afterAll as described in the Jest documentation. My goal is to complete the entire seeding process before running each individual test file.

Answer №1

After some thought, I eventually found a solution to my problem using globalSetup.

I opted for using globalSetup over managing it in beforeAll / afterAll because I wanted it to run only once per npm run test. With multiple *.test.ts files, I didn't want to seed and delete resources before each individual test.

In my jest.config.ts file, I have set the following value for the globalSetup field:

globalSetup: "<rootDir>/src/__tests__/setup/setup.api.ts",

The contents of setup.api.ts:

import 'tsconfig-paths/register';
import { seedTestDB } from "./setup.db"
import { setupTestUser } from "./testHelpers"
import { mongoConnect, mongoDisconnect } from "../../server/services/mongo"
import User from "../../models/User"

const setup = async () => {
  try {
    await mongoConnect()
  
    await setupTestUser()

    await seedTestDB()

    await grantTempAdminAccess(process.env.__TEST_USER_ID__ as string)

    await mongoDisconnect()
  } catch(err) {
    console.log(err)
    await mongoDisconnect()
  }
}

export default setup

The process involves connecting to the database, setting up a test user that will be used for all requests to API endpoints, and seeding the database. It's worth mentioning that I remove any previously seeded resources before initiating the seeding process. This approach seemed more reliable to me. Finally, I disconnect from the database.

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

Exploring the inner workings of MongoDB queries within the context of Node.js

I have a simple search query in Node.js Express.js MongoDB with Mongoose: await Model.find({}).limit(10); My question is about the process flow. Do architects first retrieve all data from Models and then limit to 10, or do they select 10 items directly fr ...

During the execution of Jest tests, a singular module is experiencing undefined imports

Encountering an unusual issue with Jest, create-react-app, and typescript. Out of the blue, Jest has stopped importing my "./ProcessStore" module correctly. This module is a dependency of something that is being imported in my tests. The error message in ...

Updating a Meteor Template Element at regular intervals using an Interval

Hey everyone, I'm just getting started with Meteor. My goal is to periodically update an element (let's say {{title}}) that comes from a collection, fetching the next title every 20 seconds or so. In regular ajax, it's easy to write a funct ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

https://i.sstatic.net/KoGto.png Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script ...

Utilizing React Testing Library for conducting unit tests on components

Can someone help me with writing unit tests for my component using react testing library, please? I seem to be stuck. What am I missing here? Here is the code for the component: const ErrorModal = (props: {message: string}) => { const { message } ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

How to efficiently update and store documents using mongoose?

Even after reviewing the official documentation, I am still unclear on how to develop methods within mongoose for creating and updating documents. What steps should I take? This is what I have in mind: mySchema.statics.insertSomething = function insertS ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...

How to Turn Off GridToolbarExport Menu in React Mui DataGrid

Can someone assist me in disabling the menu in GridToolbarExport? This is how my MUI Data Grid is set up: <DataGrid localeText={{ toolbarExport: "Export as CSV", }} disableColumnMenu={true} components={{ Toolbar ...

Exploring the capabilities of Pymongo's multiprocessing features

I am interested in utilizing multiprocessing for insert operations in pymongo. The pymongo documentation discusses the Bulk Insert Operation, as seen on this link. >>> import pymongo >>> db = pymongo.MongoClient().bulk_example >>&g ...

The Ajax query returned a successful response, yet it unexpectedly triggered an error

Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've t ...

React type-script does not trigger the onClick event for CheckBox

I have created a custom component called MyCheckBox (which I am using as a helper component). I imported this component into another one, but for some reason, the event is not being triggered when I try to click on it. Here is the code for reference: MyC ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

Transfer all specified resources from one stack to another in AWS CDK

In the process of creating two stacks, I aim to reference the resources from the first stack, such as Lambda, API Gateway, and DynamoDB, in the second stack without hard coding all the resources using Stack Props. Please note: I do not want to use Stack Pr ...

Troubleshooting image loading issues when updating the base URL in an Angular JS project

I am trying to update the base URL for my application. Currently, when I load the application, the URL shows up as http://localhost:4200/#/, but I want it to be http://localhost:4200/carrom/ instead. To accomplish this, I modified the base URL and now th ...

Exploring the process for transitioning between pages within Angular

I am working on an Angular project and I am looking to navigate to the registration page when the registration button is clicked. As a beginner, I attempted to link the registration page but encountered some issues. My goal is for the main page to disappea ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

Typescript Server Problem: Critical Error - Mark-compacts Inefficiently Close to Heap Limit, Allocation Unsuccessful - JavaScript Heap Exhausted

Whenever I run my CRA project, I consistently encounter this error in my console. It seems to be related to the typescript server. Is there a solution for this issue? 99% done plugins webpack-hot-middlewarewebpack built preview 7c330f0bfd3e44c3a97b in 64 ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...