Using the setupFiles option to set up files and execute code prior to running tests

I need to ensure that some code is executed before all tests are run.

My jest.config.js setup:

  // truncated...
  setupFilesAfterEnv: [
      "./jest.setup.ts"
  ]

The content of jest.setup.ts:

async function setUp() {
  const first = new Promise((res, rej) => {
    res('this called first');
  })
  const second = new Promise((res, rej) => {
    res('this called second');
  })
  first.then((firstRes) => {
    console.log(firstRes)
    second.then(secondRes => console.log(secondRes))
  })
}
beforeAll(done => {
  setUp().then(done => console.log(done));
  done();
})

Upon running the tests, it appears that they are not being executed in order:


 PASS  packages/dao/dao.service.spec.ts (5.532 s)
  Dao Tests
    ✓ should be defined (2 ms)
    ✓ get should return null

  .log
    Running pre-scripts for integration tests...

      at Object.<anonymous> (jest.setup.ts:56:9)

  .log
    this called first

      at jest.setup.ts:86:13

  .log
    undefined

      at jest.setup.ts:91:32

  .log
    this called second

      at jest.setup.ts:87:38

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.612 s, estimated 11 s
Ran all test suites.

The output suggests that the tests are being run before the execution of jest.setup.ts.

Answer №1

In the world of Jest, there are three main ways to achieve asynchronous behavior: using async functions, raw promises with then, and callbacks with done. It's important to note that these should not be mixed together unless absolutely necessary.

The use of setUp as async serves no purpose as it does not handle nested promises. In the context of beforeAll, done is called synchronously, and any unchained promises could potentially lead to uncaught errors.

A more suitable approach would look like this:

beforeAll(async () => {
  const first = new Promise((resolve, reject) => {
    resolve('this promise resolves first');
  })

  const second = new Promise((resolve, reject) => {
    resolve('this promise resolves second');
  });

  const resultOne = await first;
  console.log(resultOne);
  const resultTwo = await second;
  console.log(resultTwo);
})

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

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: https://i.sstatic.net/S0YyO.png Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I ...

Transitioning an NX environment to integrate ESM

My NX-based monorepo is quite extensive, consisting of half a dozen apps, frontend, backend, and dozens of libs. Currently, everything is set up to use commonjs module types, as that's what the NX generators have always produced. However, many librar ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

Exploring the retrieval of specific values through bitwise operations in Angular

Currently, I am facing a challenge in retrieving a value that I had initially saved in the database as a sum of bits. My development work is based on Angular 9 using Typescript. I have successfully managed to store the sum of bits in the database. Now, I ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

Exploring the best way to access ViewContainerRef: ViewChild vs Directive

While researching, I came across a recommendation in the Angular Docs that suggests using a directive to access the ViewContainerRef for creating dynamic components. Here is an example of such a directive: import { Directive, ViewContainerRef } from &apos ...

Navigating through Angular to access a component and establishing a data binding

I am looking for the best way to transition from one component to another while passing data along with it. Below is an example of how I currently achieve this: this.router.navigate(['some-component', { name: 'Some Name' }]); In Some ...

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

Is NATS.io compatible with React Native?

Struggling with integrating nats.io into a React Native project using Typescript has presented many challenges. Is there a way to successfully incorporate it without having to modify node_modules of nats (such as changing the "fs" import to "react-native-f ...

Issue with ambient contexts error in TypeScript constructor

What is the correct way to create a constructor in TypeScript? I have been researching and trying different approaches, but it seems like the syntax has changed. Here is my latest attempt: car.d.ts declare class Car { constructor(public engine: string ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

utilizing $inject method along with supplementary constructor parameters

After referencing the answer found here: Upon implementing the $inject syntax, my controller code appears as follows: class MyCtrl { public static $inject: string[] = ['$scope']; constructor($scope){ // implementation } } // register ...

Adding a class to a child component layout from a parent component in Angular 12 and Typescript can be achieved by using the ViewChild decorator

Incorporating the child component into the parent component is an important step in the structure of my project. The dashboard component serves as the child element, while the preview component acts as the parent. Within the parent (preview) component.htm ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

This TypeScript error indicates that the variable may be undefined (Error code: 18048)

One of the challenges I encountered in my Angular project was with an interface defined in userinterface.ts export interface Done { wordlen: number; word: string; }; I utilized this interface to populate an array like so donearr: Done[] = []; ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...