Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using:

let memoryCache = require('./lib/memoryCache');
memoryCache.init().then(() => {
   console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache()));
});

app.use('/v1', v1);
...
module.exports = app;

The memorycache.init function is asynchronous and retrieves data from a database.

module.exports = function () {
let cache = {};
return {
    init: async () => {
        console.log('called this')
        cache['repairStatus'] = formatData(await getRepairStatus());
        cache['actionStatus'] = formatData(await getActionStatus());
        cache['problemFound'] = formatData(await getProblemFound());
        cache['complaintCode'] = formatData(await getComplaintCode());
        cache['productType'] = formatData(await getProductType());
        console.log('cache is', cache)
    },
    getCache: (key) => {
        if (key) return cache[key] || null;
        else return cache;
    }
}

However, when attempting a chai-http test, the memorycache.init function runs after the test causing an error.

let res = await chai.request(server).post(url).send(testObject)

This results in a 400 error before the memoryCache initializes properly.

How can I resolve this issue?

Here is the entire test code:

const chai = require('chai');
const getTestJob = require('../../lib/testutils').getTestJob;
const chaiHttp = require('chai-http');
const server = require('../../../app.js');

chai.use(chaiHttp);
const expect = chai.expect;
const assert = chai.assert;

describe(('Api- CreateJob'), () => { let url = '/v1/job' let testSRJob = getTestJob()

 before(async () => {

 })

 beforeEach(() => {

 })

 after(async () => {
 })

 describe('*** HAPPY CASES ***', () => {
   it('successful test', async () => {
   console.log('calling test')
   let result = await chai.request(server).post(url).set('Authorization', 'auth').send(testSRJob)
   if (result.status !== 200) {
     console.log('Status: ', result.status)
     console.log('Error: ', result.error)
     assert.fail()
   } else {
     console.log('Yippie!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
   }
  });
})
})

Output:

called this

... some logging from the api tested
Error:  { Error: cannot POST /v1/job (400)
status: 400,
text: '{"message":"Create job failed","code":"E1002","errData":{}}',
method: 'POST',
path: '/v1/job'

>> then failure report in the test

cache is <cache data>
Configuration loaded on app start <cache data>

Answer №1

Have you placed the code snippet within a Mocha life-cycle hook like before() or beforeEach(), or is it inside an individual test? If it's not contained within a life-cycle hook, Node could be trying to run the Mocha tests simultaneously with memoryCache.init(), leading to app failure as initialization may not complete properly.

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

Update the div on the current page using externally retrieved information

Once again, I find myself stuck on a problem. Allow me to explain. Within this div, I have retrieved data using HTML SIMPLE DOM from another site. Like so: <div id="data">.....</div> Currently, the data refreshes whenever the user reloads th ...

Express directions to a single destination

I have implemented a middleware for routing different subdomains. You can find the middleware library here. My issue is that when I access a route other than '/', it also triggers the '/' route every time. The log below illustrates thi ...

Extract the text and value from an asp.net treeview by utilizing jQuery or JavaScript

On my website, I am using a TreeView controller. I have disabled node selection by setting SelectAction = TreeNodeSelectAction.None as I have the checkbox option enabled. However, this causes an error when trying to access the .href property of the node. T ...

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

Utilizing class attributes within multiple classes

I have created a custom class called MutationValidator as follows: const ERR_MSG = 'Error1'; @Service() export class MutationValidator { .. } This class is used in another class like so: import { MutationValidator } from './mutation ...

Looking to make some changes to the javascript countdown script

Hello, I have come across a JavaScript countdown timer code on stackoverflow that seems to be the perfect solution for my countdown timer project. The current code counts down from 30 minutes to 1 minute and then starts over again. However, it provides the ...

Troubleshooting issues with conditional routing in Node Express controller

I've created some custom logic to control access to a specific subdomain (producer.localhost:3000) Only users with the role of 'admin' should have permission to view the site, while others (with the role of 'user') should be redir ...

Ways to apply autofocus to one element once another element already has it?

I have encountered an issue while attempting to give a textarea autofocus using the autofocus attribute. Upon doing so, I receive an error message in the console that says: Autofocus processing was blocked because a document already has a focused element. ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...

Is there a way to efficiently retrieve data from an extensive BLOB column in Oracle?

I need to establish a connection between a Node Express API and an Oracle 11g Database that contains a table with a BLOB column. The challenge lies in reading this column using a SQL query, as the BLOB data can exceed 100k characters. How should I approach ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

Updating the state of a Next.JS router component with React.JS: A step-by-step guide

I've implemented a toggleswitch in my app that changes its state based on the dynamic URL parameters. For instance, if the URL includes a parameter named followType set to following (e.g. https://www.example.com/home?followType=following), I want the ...

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

"Error: Unable to locate module" encountered during the transition to Webpack 5

I am in the process of upgrading my React application to webpack version 5.72.0 (previously on 4.42.1). As part of this update, I have also upgraded webpack-cli to version 4.9.2, webpack-dev-server to version 4.8.1, and babel to version 7.17.9. However, I ...

Express.js OAuth error: "invalid_request: The `redirect_uri` parameter does not correspond to a valid URL for this application."

I am using the npm package passport-asana to send credentials to an OAuth server hosted on asana.com. After reaching the scope grant page, I successfully log into the service. However, during the callback step, I encounter the following error message in ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

Why is the location search not staying centered after resizing the map on Google Maps?

I am currently working on integrating Angular with Google Maps. I need to add some markers along with location search functionality. Additionally, I am including location information in a form. When the addMarker button is clicked, a form opens and the map ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

WebStorm unable to resolve function or method mongoose.connect()

After setting up my Node.js application, I encountered an issue while configuring the server.js file. I ensured that I added mongoose to the list of dependencies in the package.json file. However, when trying to connect to MongoDB Atlas by requiring this p ...

Sending headers after they've already been sent can lead to issues in the handling of HTTP requests in Express or Node.js

After diving into the world of NodeJS for the first time (so awesome!) and also getting acquainted with Express, I managed to get my web app/service up and running smoothly. However, things took a turn when attempting to handle multiple http requests. Here ...