Converting JSON POST data in Mocha test for an Express application

When I run my Express code from Postman, everything works perfectly. However, when I try to call it from Mocha, I encounter issues specifically with setting data in the header of a POST request. This problem only occurs with POST requests containing parameters, as GET and parameterless POST requests function as expected.

Below is the simplified code snippet that functions correctly in Postman:

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Our unit tests send POST data in JSON format
app.use(express.json());


// Helper function - common code
function ResplyWithSentence(object, adjective)
{
  console.log('GET requestuest received: object = ' + object + '; adjective = ' + adjective);

  let sentence = softwareUnderTest.MakeAsentence(object, adjective);
  sentence = JSON.stringify(sentence);
  response.status(200);
  response.set('Content-Type', 'text/json');
  response.send( sentence );
}


// Handling POST request with parameters
app.post("/makeSentenceParamsPost", (request, response) => {
  const object    = request.body.object;
  const adjective = request.body.adjective;

  ResplyWithSentence(object, adjective);
})

Here is the example of what Postman sends:

POST /makeSentenceParamsPost HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 88dfc7cc-427e-3248-ba93-286083d4c18d

{
    "object": "cat",
    "adjective": "sleepy"
}

and here is the excerpt showing how it's handled in Mocha:

it('should handle a POST request with parameters', async function(){
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "http://localhost:3000/makeSentenceParamsPost", false);      // false === synchronous/blocking
        xhttp.setRequestHeader("Content-type", "application/json");

        const object = 'hubris';
        const adjective = 'pervasive';
        let   postParameters = {'object': object,
                                'adjective': adjective};

        xhttp.onreadystatechange = function(done) {
            while(this.readyState != 4) ;       // wait until "request finished and response is ready"

            assert.isObject(this);
            assert(this.status == 200);

            assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`);
            done();
    };

    postParameters = JSON.stringify(postParameters);
    xhttp.send(postParameters);
});

The response received is The undefined is undefined.

I'm seeking assistance in identifying where I am going wrong or even tips on how to troubleshoot this issue?

Answer №1

Embrace contemporary JavaScript!

You could delve into the world of fetch, which is the modern equivalent in ES5 and utilizes Promises for smoother handling. It offers improved readability and flexibility.

const fetch = require("node-fetch");

const term1 = 'hubris'; // Avoid reserved words like object
const term2 = 'pervasive';
let parameters = {'first': term1,
                                'second': term2};
const endpoint = "http://example.com";
fetch(endpoint, {
    method : "POST",
    body: parameters,
    // -- or --
    // body : JSON.stringify({
        // user : document.getElementById('user').value,
        // ...
    // })
}).then(
    response => response.text() // .json(), etc.
    
        assert.isObject(this);
        assert(this.status == 200);
        assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`);
        done();
);

Answer №2

To fix the issue, make sure to capitalize the "T" in "Type" like so:

xhttp.setRequestHeader("Content-Type", "application/json");

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

Can anyone suggest an effective method for displaying images using JavaScript by specifying a route and filename?

Currently, I have the following code snippet: const route = '/Images/Banner/'; const slides = [ { name: "banner-01", url: `${route}banner-01.png` }, { name: "banner-02", url: `${route}banner-02.pn ...

pop-up window that shows chosen choices using javascript or ajax

I have a specific HTML code that allows users to select multiple options. I would like these selected options to be displayed in a popup or a div in real-time as the user makes their selections. I have attempted using a selectbox with checkboxes, but extra ...

Error: Modification of unique identifier not permitted

Many have tried to tackle this issue, but I have yet to come across a solution that is widely accepted. I am currently facing an error when trying to update a document in MongoDB using Mongoosejs. The error message I receive is: { [MongoError: Mod on _id ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Utilize Node.js to simultaneously connect with several APIs

Consider a scenario where multiple APIs need to be called in parallel using promise.all(). The issue arises when promise.all() rejects if any API fails. In this case, instead of giving up on failed APIs, I want to retry them until they succeed. However, ...

The function of jQuery's .prop('defaultSelected') appears to be unreliable when used in Internet Explorer 9

Below is the code I am currently using: $selects = $('select'); $selects.val( $selects.prop('defaultSelected')); The purpose of this code is to reset the values of all select elements on my webpage. However, I am facing an issue in IE ...

Encountered a problem with Node and Mongoose: "TypeError: Object.keys called on non-object" error when trying to save

Within the user schema below, there exists a foobar.events field. I am attempting to add new hashes (received from an API POST request) to this field. var userSchema = mongoose.Schema({ foobar: { id : String, token : ...

The backtick is not functioning correctly when trying to append the result in the Internet Explorer browser

I am using the .html method to append HTML content to a specific div ID within my file. <html> <head> Title <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...

How can I use JavaScript or JQuery to retrieve the HTML content as a string from a specific URL?

How can I extract the URL of a link from a webpage and add it to my code without an ID for that specific link? Is there a way to search based on the content within the <a> tag? ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...

Automatically update the table in Python Flask every minute

I need help with my Flask code below. I want to automatically refresh the table data every 60 seconds. I have included the Setinterval function in HTML, but for some reason, it's not refreshing as expected. I'm struggling to pinpoint the exact is ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

What is the best way to display the name of the user who has logged in using Facebook login?

After successfully implementing Facebook login using Passport.js, I encountered a problem with displaying the user's name in my React component. Despite correctly storing the id and name in the database on the backend, I struggled to retrieve and disp ...

What is the best way to fetch a partial JSON response object from an API using JavaScript?

Currently, I am utilizing the One Bus Away API, returning a response object in this format: { "code": 200, "currentTime": 1504150060044, "data": { "entry": { "arrivalsAndDepartures": [ {AnD_item1 ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Load content from a remote page using AJAX into a JavaScript variable

Looking to retrieve a short string from a server without direct access to the data in XML or JSON format. Utilizing either .load or .ajax for this purpose, with the intention of parsing the data into a JavaScript array. The target page contains only text c ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...