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

What is preventing WebRTC from re-establishing connection after being disconnected?

In my current React web application project, I am implementing a feature where users can engage in group calls using WebRTC through a NodeJS server running Socket.IO. The setup allows for seamless joining and leaving of the call, similar to platforms like ...

Getting your JQuery ready() statement right is crucial for the proper

I have come across all three variations below: $().ready(); $(document).ready(); $(document.body).ready(); All of them seem to work, but I'm wondering which one is the most appropriate or recommended to use when considering the usage of the ready() ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

Steps for generating a dropdown menu using API JSON information

I'm new to using Webapi with AngularJS. I have a URL that returns data in JSON format, and I want to extract only the employee names from the data and display them in a dropdown list using AngularJS. Any assistance would be greatly appreciated. ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

Execute the calculation on the user's AWS account

In my Node.js and Vue.js project, the goal is for a user to input their AWS credentials, provide a link to an online data source containing a large amount of data, and run an algorithm on this data using their provided AWS account. I am facing two challen ...

Retrieve user information using a GET request in an Express server

I am working on creating a GET API route to retrieve all tasks assigned to a specific user. However, when I test the call (http://localhost:4000/api/taskuser/getalltasks?userId=5bfe4af425ddde2b04eb19c6), I am not getting any errors but still receiving all ...

Utilizing Contentful along with Nuxt.js causes the error message "Required accessToken parameter missing"

I created a webpage that pulls information from Contentful. Although the data is being retrieved correctly, buttons utilizing functions from methods are not working. Additionally, real-time updating of variables (such as using v-model) is not functioning. ...

I am experiencing an issue where the Mongo item ID is not being successfully passed through the REST API

Recently, I've been working on developing a blog site for my class project. The main goal is to create a REST API for the blog site. I have successfully managed to display data from the database using .ejs views, except for one issue. I am facing diff ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

setTimeout executes twice, even if it is cleared beforehand

I have a collection of images stored in the img/ directory named 1-13.jpg. My goal is to iterate through these images using a loop. The #next_container element is designed to pause the loop if it has already started, change the src attribute to the next im ...

Eliminating the nested API call within a loop

After making an API call to retrieve a set of data such as a list of users, I noticed that I am implementing a for loop and within it, I am making another API call to obtain each user's profile details based on their ID. I understand that this approac ...

Ensuring jQuery filter() works seamlessly with Internet Explorer versions 6, 7, and 8

On my webpage, I have implemented an ajax call using the jQuery library to handle a specific task. After making the ajax call, I need to parse the response message that is returned. However, I encountered an issue with Internet Explorer versions 6, 7, and ...

What is the best way to integrate ReCaptcha into a Nextjs contact form?

Currently, I am in the process of designing a portfolio website that includes a contact form for visitors to get in touch with me. I have successfully integrated SendGrid for email transfer, but my main concern now is spam. Despite my efforts to find a sol ...

Fetching Date and Time from the Internet using PHP

While I understand that similar questions have been asked numerous times before, I have yet to find a solution that fits my specific needs. My question is regarding how to retrieve the current date and time from the internet rather than relying on the loc ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...

Am I utilizing React hooks correctly in this scenario?

I'm currently exploring the example, but I have doubts about whether I can implement it in this manner. import _ from "lodash"; ... let [widget, setWidgetList] = useState([]); onRemoveItem(i) { console.log("removing", i); ...

Increased impact of dynamically added elements following page transition

After implementing dynamic functionality from jQuery in my code, I encountered an issue where if I navigate back one page and then return to the original page containing the added elements, they seem to trigger twice upon clicking. To troubleshoot, I incl ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...