Can a promise-based test run automatically when testing Express with Mocha?

I have been facing a puzzling situation with my test files. When I have only 'test1.js' present, Mocha reports that there are no tests passing, giving me a "0 passing" message. However, if both 'test1.js' and 'test2.js' are present and both depend on promises, once again, no tests run and Mocha reports the same "0 passing". Surprisingly, when I modify one of the tests to not use a promise, Mocha runs both tests successfully. What could be causing this strange behavior? Here are the files in question:

index.js:

require('./server').then( function(server) {
  server.listen(8080, function() {
    console.log("Started server");
  });
);

server.js:

var express = require('express');
var server = express();

module.exports = new Promise((function(resolve, reject) {
  return resolve(server);
}));

test1.spec.js:

require('./server').then(function(server) {
  describe('Test Suite #1', function () {
    it('should run test #1', function testSomething(done) {
      return done();
    });
  });
});

test2.spec.js (using server.js as promise, tests do not run):

require('./server').then(function(server) {
  describe('Test Suite #2', function () {
    it('should run test #2', function testSomethingElse(done) {
      return done();
    });
  });
});

test2.spec.js (server.js is not used as promise, both tests run):

var server = require('./server');
describe('Test Suite #2', function () {
  it('should run test #2', function testSomethingElse(done) {
    return done();
  });
});

To execute these tests, make sure you have nodejs, Express, and Mocha installed, then run the following command:

% mocha "*.spec.*"

Although the examples provided here may not utilize the 'server' variable, in actual tests, a promise needs to be returned because sometimes 'server.js' accesses remote systems for configuration data. While I can find workarounds for this issue, any guidance or explanation regarding what is happening would be greatly appreciated!

Answer №1

Ensuring that all your tests are described and defined asynchronously is crucial for Mocha to recognize them. If you need to set up any asynchronous processes, make sure to use either the before or beforeEach functions:

describe('Test Suite #1', function () {
  var server;
  before(function(done){
    require('./server').then(aServer => {
      server = aServer;
      done();
    });
  });
  it('should execute test #1', function testing(done) {
    return done();
  });
});

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

I encountered an issue with a missing script while attempting to start npm to generate a React application

I am attempting to start the React server using the command npm start However, I encounter a missing script error when I run this: λ npm start npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! C:\User ...

Issue with docker-composer module not being detected specifically on windows operating system

We are currently in the process of setting up a container running node.js with docker (specifically docker-compose, as we plan to incorporate mongodb later). Our approach involves copying the package.json in the Dockerfile and then creating a volume mount ...

Is there a way for me to monitor the progress of a node.js request?

I have a node.js app that creates an image, let's call it "Image A", and then uses this "Image A" to create another image, which we'll refer to as "Composition A". When the server receives 4 image requests almost simultaneously for Composition A, ...

How to trigger a function in Node async.map once all tasks have finished executing?

I currently have this code snippet: function get_status(){ try { /* GET - status */ async.map(['http://url1.com/', 'http://url2.com/', 'http://url3.com/'], function(value, callback) { /* GET - request status */ ...

Interrogate Firebase to retrieve the Key

I'm attempting to query firebase, and I am encountering challenges when trying to retrieve a unique key from the record. While my filter is functioning correctly, I am struggling to identify the object property names within the data. The .key() method ...

Encountering the error "Invalid parameter: redirect_uri" while attempting to authenticate with KeyCloak using NODE.JS

In my Node.JS (express) project, I am utilizing a helpful NPM package called keycloak-connect to establish a connection with a keycloak server. While trying out the default protection mechanism for a specific route: app.get( '/about', keycloak ...

CSRF Error: Unauthorized Access Detected in Express and NodeJS

I've been attempting to create CSRF tokens in my Express application. Despite looking at similar questions, I haven't found a solution. Below is the code snippet from my app.js file: var app = express(); var connect = require('connect' ...

Setting up Twilio integration on a Parse Server deployed on Heroku

I am currently running a successful Parse Server on Heroku and am attempting to set up my Twilio cloud code. However, the moment I include var twilio = require('twilio')(twilioAccountSid, twilioAuthToken); in my main.js file, the application stop ...

Attempting to understand how to implement mongoose relationships in REST API development

I am struggling to grasp the concept of setting up routes in Express for a hierarchical data structure within my app. Despite researching via Google, code snippets, and tutorials, I have not been able to find examples that match the complexity of what I am ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

exploring the capabilities of sockets in PHP, reminiscent of the functionality found in Node.js

I recently downloaded and tried out a basic chat app with Node.js: https://github.com/socketio/chat-example The app is functioning properly. The server-side code is quite straightforward: var app = require('express')(); var http = require(&ap ...

Using Filepond to upload images in an Express project with EJS integration

Currently, I am working on a project that utilizes express.js for backend functionality and ejs as the rendering template for frontend. As part of this project, I have uploaded some images using filepond which were then converted to base64 format. However, ...

What is the process for connecting a folder in an express app to my Apache 000-default.conf file on a Ubuntu server?

I already have a domain and I am looking to connect my folder to my Apache configuration file so that I can use certbot. However, I am not sure how to properly set up the connection. This is what I have tried so far: <VirtualHost *:80> # The ...

Is it feasible to run two applications simultaneously on the same port using express.js?

Can two apps run on the same port using expressjs? Node app1.js: const app = express(); app.get('/api/v1/foo', (req, res) => { res.json(...); }); express.listen(3000); Node app2.js: const app = express(); app.get('/api/v1/bar', ...

Issues arise with AngularJS showing images fetched from an API

Currently, I am facing an issue where I am trying to display images from a REST API but keep receiving a "error 403" message. Here is the link to my JSFiddle. Please take a look, as I have attempted using both <img src=""> and ng-src='', bu ...

How can I send a Google Chat message using a non-automated account, not a chatbot?

I'm facing challenges while attempting to send notifications through Google Chats. The existing documentation has left me with several issues: It demands a paid service account, which I don't possess and won't be acquiring It mandates the u ...

[AWS Lambda SDK] - Executing Lambda Function - Processing Payload Response as Unit8Array - Conversion to String

Currently, I am utilizing the npm package @aws-sdk/client-lambda to invoke Lambdas. In my setup, I have two Lambdas - Lambda A and Lambda B, with Lambda A responsible for invoking Lambda B. The invocation of Lambda B from Lambda A is done through the foll ...

Is there a way to selectively add elements to the Promise.all() array based on certain conditions?

Here is the code snippet that I have written: I am aware that using the 'await' keyword inside a for-loop is not recommended. const booksNotBackedUp: number[] = []; for (let i = 0; i < usersBooks.length; i += 1) { const files = await ...

Differences between app.get(name) and app.get(path, [callback...], callback) when using ExpressJSWhen

Just starting out with Express and after reading through the API documentation, it appears that there are two app.get() methods. One is used to retrieve the value of a variable, while the other is typically used to handle HTTP GET requests. What sets thes ...

Converting ExpressJS Function for Multipart Uploading to AWS Lambda

Looking for advice on converting this Express.js function to AWS Lambda for Node.js 18. const upload = multer() // Write received chunk to S3 bucket app.post('/upload', upload.single("file"), (req, res) => { const { index, fileNam ...