JestJS: Async testing isn't halted

I am facing two issues with my jest test:

  1. Is there a way to define the Content collection only once instead of repeating it inside the test?
  2. I encountered this error:

    Jest did not exit one second after the test run has completed. This usually indicates that there are unresolved asynchronous operations in the tests. Try running Jest with --detectOpenHandles flag to debug this problem.

I'm puzzled as to why my async code is not being stopped...

import resolvers from 'resolvers/'
import Db from 'lib/db'
const db = new Db()

describe('Resolver', () => {
  let token

  beforeAll(async () => {
    await db.connect()
  })
  beforeEach(async () => {
    token = 'string'
    await db.dropDB()
  })
  afterAll(async () => {
    await db.connection.close()
  })

  describe('articleGetContent()', () => {
    test('should return dataset', async () => {
      // SETUP
      const Content = db.connection.collection('content')
      const docs = [{
        // some content...
      }]
      await Content.insertMany(docs)
      // EXECUTE
      const result = await resolvers.Query.articleGetContent({}, {
        id: '123,
        language: 'en'
      }, {
        token
      })
      // VERIFY
      expect.assertions(1)
      expect(result).toBeDefined()
    })
  })
})

resolver

import { articleGetContent } from '../models/article'

export default {
  Query: {
    articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)
  }
}

This is what my db class looks like

db.js

export default class Db {
  constructor (uri, callback) {
    const mongo = process.env.MONGO || 'mongodb://localhost:27017'
    this.mongodb = process.env.MONGO_DB || 'testing'
    this.gfs = null
    this.connection = MongoClient.connect(mongo, { useNewUrlParser: true })
    this.connected = false
    return this
  }

  async connect (msg) {
    if (!this.connected) {
      try {
        this.connection = await this.connection
        this.connection = this.connection.db(this.mongodb)
        this.gfs = new mongo.GridFSBucket(this.connection)
        this.connected = true
      } catch (err) {
        console.error('mongo connection error', err)
      }
    }
    return this
  }

  async disconnect () {
    if (this.connected) {
      try {
        this.connection = await this.connection.close()
        this.connected = false
      } catch (err) {
        console.error('mongo disconnection error', err)
      }
    }
  }

  async dropDB () {
    const Content = this.connection.collection('content')
    await Content.deleteMany({})
  }
}

Answer №1

When it comes to the second question, I recommend checking for any related issues on GitHub. Typically, the issue is outlined in the debug log. Jest operates with promises, so it's crucial to ensure all async operations are in a resolved state.

In your scenario, where you have an open DB connection, it's important to implement a separate method called disconnect for your DB class. You may refer to documentation for guidance. To tidy up, include this method within the afterAll hook:

afterAll(() => db.disconnect());

A helpful example can be found towards the end of the page here.


Regarding the first question, the solution depends on the functionality of your dropDB method. If it involves dropping a collection, consider storing a reference to this collection externally for automatic recreation. It would also be beneficial to review and share more details about this method.


Furthermore, if there were issues with your asynchronous test setup, you might find some useful insights here. One key step is to kick off the test with: expect.assertions(number)

The use of expect.assertions(number) ensures that a specified number of assertions are executed throughout a test, particularly valuable when evaluating callbacks in async code.

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

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

What is the method for converting this pattern into a JavaScript regex?

This code is functioning properly newRow.replace('[[' + key + ']]', item); I attempted to use regex for the replacement, but it is not working as expected newRow.replace('/\[\[' + key + '\]\]/' ...

Vertical Positioning of Tabs in Materialize CSS

My current challenge involves creating vertical tabs using materialize CSS, specifically in regards to positioning. The desired outcome is for the content to align at the same level when clicking on TAB 3. An example of the expected result can be seen in t ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Exploring Symfony2: Enhancing user experience with dynamic form submission and dropdown menu updates

Starting from the beginning. I have a tab-panned layout with links. Upon clicking a link, a drop-down checkbox form is injected directly into the HTML through $(".dropdown-toggle").click(function() { var projectId = $("#permission-form").attr("data-p ...

Updating variable values in AngularJS while navigating through routes

How can I dynamically set the flag icon inside the page header based on the selected language using AngularJS? The language selection is done in a separate .htm file and all managed by AngularJS routing. My application has a single controller called "appCo ...

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

Encountering a Next.js event type issue within an arrow function

After creating my handleChange() function to handle events from my input, I encountered an error that I'm unsure how to resolve. Shown below is a screenshot of the issue: https://i.sstatic.net/fWJA2.png I am currently working with Next.js. In React ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

The error message "No bean named 'mongoTemplate' found in MongoDB Spring" appeared on the screen, indicating that a

This question pertains to using Mongodb and Spring, a common issue that I typically find solutions for on various platforms. However, this time none of the existing answers seem to address my specific problem... I am at a loss as to what to do. Here is th ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

Adjust the color of a selected edge in Three.js

let cubeEdges = new THREE.EdgesHelper(cube, 0xff0000); cubeEdges.material.linewidth = 5; scene.add(cubeEdges); A cube has been created using the following code: new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200, 1, 1, 1, materials), new THREE.MeshFaceMa ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

Ways to confirm that the function handed over as a prop to a Vue component operates asynchronously

How can I determine if a prop Function is asynchronous? Consider the following prop in my component: callbackFunction: { type: Function, default: null, }, Is there a way to validate this and ensure that the provided Function i ...

Learn how to customize button styles in ExtJS with the pressedCls configuration option

Is there a way to change the color when a button is pressed? I tried using the pressedCls config but it didn't work. How can I fix this issue or is there another method to set the CSS when a button is pressed? Thank you so much! Javascript: Ext.crea ...

Encountering BeanCreationException when autowiring Mongo repository in Spring boot application

I've come across various questions and answers regarding autowire and BeanCreationException, and it appears that the common culprit is often the ComponentScan annotation and the project structure. However, I'm still unable to pinpoint why my app ...

Secure a RESTful API with a Keycloak access token in a Node.js environment

I have implemented a REST API in Node.js and integrated the keycloak-connect npm package for security. I have configured the Node.js middleware to work with the keycloak middleware. var express = require('express'); var router = express.Router(); ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...