Testing an Express route using Mocha and Chai: A comprehensive guide

I am currently developing an express app that renders views with filtered data.

Here is my current route:

router.get('/user/name/:name', (req, res) => {
    return serverUtil.getUserByName(req.params.name).then(success =>{
        res.render('partials/users/user', {user: success});
    }).catch(err =>{
        res.render('partials/users/user', {error: err});
    });
});

While I am able to send a response using res.render, I am unsure of how to test it.

This is how my Mocha test looks like:

  it('Should post to user/name/:name', function(done){
    chai.request('http://localhost:5050')
      .get('/user/name/Britney')
      .end((err, res) => {
          console.log("res ", res.body); // empty
          exp(res).to.be.a('object');
          done();
        });
  });

However, when I change the route to:

router.get('/user/name/:name', (req, res) => {
    return serverUtil.getUserByName(req.params.name).then(success =>{
        res.send({user: success}); //Change this
    }).catch(err =>{
        res.render('partials/users/user', {error: err});
    });
});

The test passes as expected, but the application does not function properly.

Can anyone guide me on how to test the route with res.render and validate the passed data?

Answer №1

Finally, I have identified the solution to my issue.

Initially, it is essential to utilize cheerio for this task. When using the res parameter in the .end() callback, I retrieve the HTML from res.text. Previously, I mistakenly searched for it within res.body but the correct code is as follows:

  it('Should post to user/name/:name', function(done){
    chai.request('http://localhost:5050')
      .get('/user/name/Britney')
      .end((err, res) => {
          res.should.have.status(200);

          exp(res).to.be.a('object');

          let $ = cheerio.load(res.text);
          let textid = $('#textid').val(); //the id of my id field

          exp(textid).to.have.equal('a0ece5db-cd14-4f21-812f-966633e7be86'); //true
          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

Maintaining personalized variable values for individual connected clients in Node.js: What's the best approach?

I have recently started working with Node.js and I am using Visual Studio 2015 with the Basic Node.js Express 4 app template. After setting some values through a post request from the client, I noticed that when I open another tab and send another post re ...

What is the best way to provide execution arguments to an app through PM2?

While attempting to start my app using pm2, I encountered an issue with passing arguments. Despite using the command pm2 start app.js -- dev, I was unable to pass the argument successfully. Interestingly, this worked without any issues when using forever ...

nodejs SSL error: missing request header

When I utilize req.headers.host in my Express.js and Nodejs 6 application on an SSL enabled server, I encounter an error stating that the header is undefined. This is my code: if(req.headers.host.indexOf('domain.com')>-1){ ...... } The er ...

Can Tailwind CSS be used in conjunction with express's sendFile function?

Attempting to transmit an html file via express but encountering issues with including tailwindcss Ensured correct setup (or so it seems) Could sendFile be unable to send tailwindcss This is the current express setup // express setup const app = express ...

I encountered difficulties with utilizing res.send and res.download in Node/Express because the headers were already set

I have recently started working with Node and I am facing an issue where I need to render a webpage when accessing 'localhost:1337/download/open' along with downloading a file. I know that headers can only be set once, which is the error I keep e ...

Steps for defining local variables accessible across all EJS templates:1. Begin by creating a helper function

When setting local variables in the /login router as shown in the code snippet below: res.locals.username = data[0].username;, I have checked the output using console.log for both data[0].username and res.locals.username, and it correctly displays the user ...

I am encountering an issue where my React application is unable to establish a connection with my Express application when I dockerize them together. Can anyone

Currently tackling a project for my university that involves using a react app for frontend, an express app for backend, and mongodb as the database. Previously, I would launch the express app and react app separately before dockerizing them, and everythin ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

Encountering an error while initializing the JWT verify module: Unable to access the 'header' property of an undefined object

I tried to implement JWT authentication following a tutorial video. You can watch it here: https://youtu.be/2jqok-WgelI?t=4284 However, I encountered an error when attempting to use the verifyToken module at around 1 hour and 11 minutes into the video. ...

What is the process for adding values to an existing JSON object in MongoDB?

I need to calculate the expenses for a specific category in a particular month. Below is an example of my data stored in MongoDB: { "2022":{ "January":{ "Food":30, "Traveling":0, ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

Issue encountered while retrieving data in React Native app from an express server

I am currently in the process of building an android application that fetches data from a local server. I have encountered no errors thus far, but unfortunately, I am not receiving the requested data. To provide some context, my frontend is built using Rea ...

What could be causing my Node.js express application to crash with the error message 'This Serverless Function has crashed' when trying to connect to a Sequelize Database on Vercel?

I'm having trouble deploying my Node.js express app to vercel. I keep encountering this error message: "This serverless function has crashed." I can't seem to pinpoint the issue. In my root project folder, I have an index.js file where I initial ...

Misplacing a cookie while trying to request it from one subdomain to another subdomain

Recently, I've been encountering a strange issue involving the disappearance of cookies. In the past, I utilized AWS for both my frontend and backend infrastructure. View previous setup Due to deployment complications (specifically prolonged fronte ...

Node.js/Express.js is throwing an error: 'undefined is not a function'

I recently started using 'express-namespace' to organize my routing in a cleaner way. Below is the snippet of code I have implemented. .. 9 var controllers = require('./controllers'); 10 require('express-namespace'); .. 46 ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...