Testing URL Parameters in JEST with an API

Seeking integration tests using Jest for an API endpoint. Here's the specific endpoint:

http://localhost/universities/ucla/class/2013/studentalis/johndoe
. When tested with a put request, it returns 201 on Postman.

However, the testing encountered a timeout issue due to an error in the updateStudent.js file. The problem lies in parsing the URL parameters:

function getQuery(req, studentid, id) {
  return {
    universityName: req.params.universityName.toString(),
    class: req.params.class.toString(),
    studentAlias: req.params.studentAlias.toString()
  };
}

The error message received is "TypeError: Cannot read properties of undefined (reading 'toString')". Upon investigation, it was found that req is indeed an object, but req.params is empty leading to undefined values in

req.params.universityName.toString()
. This indicates a probable incorrect way of setting the URL params. Any suggestions on the correct syntax?

Answer №1

By not specifying any route parameters, the req.params will be empty.

Route parameters act as named URL segments that capture values specified in the URL. These captured values are then stored in the req.params object, with the route parameter name serving as their keys.

To define route parameters, simply include them in the path of the route within your server.js or index.js file. For example: /path/:name, where 'name' is the route parameter.

const express = require("express");
const updateStudentRoute= require('../handlers/updateStudent');
const app = express();
app.use(express.json());
// Use `put` method instead of `use`
app.put('/university/:universityName/class/:class/studentalias/:studentAlias', updateStudentRoute);

app.listen(2000,function(){  
   console.log("Server is running on port 2000");  
});

Additionally, ensure you use app.put rather than app.use, as app.use() is meant for applying middleware to your application.

Once familiar with route parameters, learn how to test them:

In your test file:

const supertest = require("supertest");
const request = supertest("http://localhost:2000");

describe('Update Student Details in Database', () => {
    it('Update Student Details in Database', async() => {
        // const updateStudentRequestBody = require('./updateStudentRequestBody'); put method does not have a body
        const response = await request.put(`/university/ucla/class/2013/studentalias/johndoe`); // You can replace :name with actual values here
        expect(response.statusCode).toBe(201);
    });
});

It's not necessary to pass the app instance each time when testing the same host. Simply reassign the request variable with the URL initialization as a new Test is created per request.VERB() call.

Lastly, remember to set the response code as 201, as by default Express responds to all endpoints with status code 200.

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

Ajax: The requested resource does not have the 'Access-Control-Allow-Origin' header. As a result, access is not permitted from origin 'null'

I recently started learning about ajax and followed a tutorial. However, I encountered an error when trying to run an HTML file along with a linked JavaScript file. Since browsers cannot make requests to file://, I have set up an http-server on port 8080 ...

How can I prevent a hyperlinked element from being clicked again after it has been clicked using JavaScript or jQuery in PHP

I am struggling with disabling the href after it has been clicked. Can someone please assist me with this? It is crucial for me to complete this PHP program. Style.css .disabled { pointer-events: none; } ...

How can you efficiently identify and resolve coding errors or typos in your code?

While practicing node.js and express.js, I encountered an issue with finding typos. One such instance was when I mistakenly typed: const decoded = jwt.veryfy(token, config.get('jwtSecret')); instead of jwt.verify. Even though I eventually disc ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

Customizing React components based on API data

const LinkList = () => { const [links, setLinks] = useState([]); const url = 'http://localhost:5000/xyz'; const hook = () => { console.log('effect'); axios .get(url) .then(respo ...

Utilizing the same WebDriverJS instance repeatedly

As a beginner in Selenium, I successfully launched a website using the following Node.js code snippet: var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); console ...

`How can we access the Passport user in the main.js file and incorporate middleware?`

I am trying to retrieve the user information of the logged-in user. The serialize and deserialize functions for the user are functioning correctly. I can see all the information when I log req in the console. Even though the user information is included i ...

"Encountering a Type Error while attempting to destructure elements within ReactJS

Issue Upon querying objects from the GraphQl server and logging data, I can see the objects in the console. However, when attempting to destructure it as data: { getPosts : posts }, a type error is returned. Furthermore, trying to use map directly on data ...

Timeout when making an HTTP request

One question I have is regarding socket timeout in NodeJs. To address the issue, initially, I included the following code : req.socket.once('timeout', function(err) { imports.logger.warn('Express socket timeout.', err); ...

JavaScript ECMAScript 6 - WARNING: "Decorators can only be applied to a class when exporting"

In ECMAScript 6, I am attempting to export a function so that I can import it and utilize it in other files for the sake of writing DRY code. However, an error message is appearing: You can only use decorators on an export when exporting a class (16:0) ...

The suspense fallback function seems to be missing in NextJS 13

I'm in the process of creating an application to demonstrate the functionality of Suspense in Nextjs 13. However, I'm encountering an issue where the Suspense fallback is not appearing during loading. Below is the code for page.js import React, ...

What is causing this console to output twice?

My Objective: I aim to utilize Node.js to launch two child processes sequentially at a specific time, displaying their `stdout` as it streams, occasionally alternating between the two processes. The Desired Output: `Proc 1 log # 1` `Proc 1 log # 2` `Pr ...

Monitor the output of a spawned process that is currently in a state of awaiting user input

In my Swift program, I am logging information to the stdout while waiting for a termination signal of \n. The input is requested immediately upon starting and the info is logged 1~2 seconds later: fetchAndLogDataInBackground(); // will print some dat ...

Converting a floating point number to a 4-byte hex string in JavaScript and reversing the process

I have received a hexadecimal data from the server side that is supposed to be in float format. I am trying to convert these hexadecimals into floats using JavaScript, but so far I have been unable to find a suitable method. Can anyone provide assistance ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

What is the best method for retrieving data through an ajax call in my modular JavaScript setup?

Working with a basic modular JavaScript structure, my goal is to request a random quote from an API and display it on an HTML page using Mustache.js. I previously achieved this without the modular approach, but now I'm attempting it in a more structur ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Flickering observed in AngularJS UI-Router when navigating to a new route

In my AngularJS ui-router setup, I am facing an issue with flickering during state changes while checking the authentication state. When a user is logged in, the URL /#/ is protected and redirects to /#/home. However, there is a brief flicker where the c ...

Is there a built-in function in Firefox that can retrieve a list of all indexedDB names stored in the

When working in chrome, I utilized the window.indexedDB.databases() method to retrieve all indexedDb names. However, this same method does not seem to be functioning in firefox. In an attempt to resolve this issue, I will explore alternative methods such ...