Experiment with express router using mocha testing framework

Encountered an unusual routing behavior in Express (node.js).

Attempting to test an API.

The server mounts:

app.use("/", productRouter);
app.use("/", testRouter);

productRouter.post("/products", ...);
testRouter.post("/test", ...);

If I POST to:

http://localhost:MYPORT/test
http://localhost:MYPORT/products

Everything functions correctly.

However, when running this Mocha test:

const app = require("../src/index");

describe(" ====== Test for argumentMiddleware: a factory to check request arguments ======", () => {
  describe("requiredArgument middleware", () => {
    it("it should return error if requiredArgument is not in the body of request:", done => {
      let requestBody = {
        argument: "product"
      };
      chai
        .request(app)
        .post("/test")
        .send(requestBody)
        .end((err: Error, res: any) => {
          res.should.have.status(400);
          console.log(err.message);
          done();
        });
    });
    it.skip("it should pass if requiredArgument is in the body of request: ", done => {
      let requestBody = {
        requiredArgument: "product"
      };
      chai
        .request(app)
        .post("/test")
        .send(requestBody)
        .end((err: Error, res: any) => {
          res.should.have.status(200);
          done();
        });
    });
  });
});

It seems to be POSTing to /products instead of /test. A console.log inside /products is triggered. Why is it routing to that endpoint? Could it be due to its declaration order?

Answer №1

Something does not seem right with this section:

app.use("/", productRouter);
app.use("/", testRouter);

Have you tried changing the ("/") part for testRouter to something like this?

app.use(testRouter);

Alternatively,

app.use("/api", testRouter);

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

In what location can event listeners be found in npm packages?

For a while now, I've been immersed in the world of coding as I work on creating my very own IRC bot using nodejs. This project serves as an invaluable learning experience for me, and as I navigate through the process, I constantly encounter event lis ...

Generating a distinct identification for a row using JavaScript

Here is my JavaScript function for dynamically adding new rows to a table in HTML. I want each row to have a unique ID. This is the code I have so far: $(document).ready(function(){ var html = '<tr><td class="cb"><inpu ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

Click Function for Modifying the Content of a Popup Window

I'm a beginner in JavaScript and I need help figuring out how to achieve the following task. Essentially, my goal is to have lines of code like this: <a onclick="JavascriptFunction(0000000)"><img src="image1.png"></a> The number w ...

What is the best way to organize components in ReactJS?

Confusion I am seeking clarification on the placement of my aside code. It is meant to render components such as searchInput and menuStudy. I was considering placing it in the container's folder, but it does not serve any specific purpose like hand ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

What is the best way to automatically remove documents from a MongoDB database after a specified period of time?

Can someone guide me on how to delete a document from mongo DB after a timeout? I have a method that works, but it results in an error message and the server stops running. Could you suggest a better approach and explain why this one is causing issues? He ...

Transform FormData into a collection of objects

I am working on a form where the same set of fields repeats multiple times. After filling out the form, it is sent as FormData to the back-end. Currently, I have named the fields in the form like this: <input name="firstname" /> <input ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

Determine the size of a file in either megabytes or kiloby

I need to determine the size of a file in either megabytes if the value is greater than 1024 or kilobytes if less than 1024. $(document).ready(function() { $('input[type="file"]').change(function(event) { var _size = this.files[0].si ...

Struggling to retrieve a JSON object from an Express and Node application, only receiving an empty result

Can anyone assist me? I'm having trouble with the res.json() function in my code. It seems to work after the first request, but not after the second. Right now, my application is quite simple - it scrapes user data from social media platforms like Twi ...

Never miss out on the broadcast!

I am working on an Angular Project and I am trying to create an Authentication mechanism. Here is the code for my Login controller: angular.module('authModule') .controller('LoginCtrl', function($rootScope, $location, loginRESTService, ...

Javascript only select values from the initial row of the table

I have a database that I am using to populate a table with results. To interact with these results, I utilize JavaScript in addition to PHP for retrieving values from the database and displaying them in the table. <table id="datatable" class="table tab ...

Investigating TLS client connections with node.js for troubleshooting purposes

I am currently facing an issue while setting up a client connection to a server using node.js and TLS. My query revolves around how I can gather more information regarding the reason behind the connection failure. It would be great if there is a way to ob ...

Clicking anywhere outside a popup menu in JavaScript will deactivate a toggle and hide it

I have three different menu options: home,Clinic, and About. When I click on the Clinic option, a Megamenu appears, and if I click on it again, the Megamenu is hidden. I want the Megamenu to hide when clicking anywhere on the webpage. The issue is that cu ...

Having trouble showing the JSON data on the HTML page

I have successfully managed to use $http.get in my script to retrieve JSON data, which I receive in Object Form. However, I am facing issues when trying to access the values in the array. https://i.sstatic.net/skKjq.png Below is a snippet of my AppCtrl p ...

What is the best way to loop through unsorted JSON data and organize it into an array?

Currently, I am extracting data from an API in the form of a JSON object. The issue is that this JSON data is unordered by default. I am aware that JSON is meant to be unordered, but I would like to figure out how to loop through these keys and organize ...

Triggering a function without the presence of an actual event

I need to come up with a solution for reusing a function triggered by an event binding. This problem stems from browsers remembering checkbox states, which is why I have to call the function on document load. One approach could involve wrapping setGrid() ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Printing an array from JavaScript to an EJS template: Tips and Tricks

I'm currently working on a database-driven website that focuses on searching through people's profiles. When attempting to display information from a database query, I am encountering the issue of receiving [object Object]. Below are snippets o ...