Ensure secure access by including an authentication token in the request header while leveraging supertest alongside jest and express

I am currently working on testing the routes within my express application that are secured by a jwt middleware. To attempt to retrieve the jwt token in a test setup, I have utilized a simulated request within a beforeAll function:

let token = "";
beforeAll((done) => {
    supertest(app)
        .get("/authentication/test")
        .end((err, response) => {
            console.log(response.body); // "fewiu3438y..." (token successfully retrieved) 
            token = response.body.token; // Attempted to update the token variable with jwt token
            done();
        });
});
console.log(token); // "" (Token variable not updated) 

As a result, when trying to execute subsequent tests, authentication fails due to the absence of a valid token for headers:

    describe("Simple post test using auth", () => {
        test.only("should respond with a 200 status code", async () => {
            console.log({ POSTTest:token }); // "" still not set, causing test to fail.
            const response = await supertest(app).post("/tests/simple").send();
            expect(response.statusCode).toBe(200);
        });
    });

Is there an effective way to update a variable or set all headers using a beforeAll? Alternatively, is there a more efficient method that I may be unaware of?

Answer ā„–1

Consider implementing an async function within a beforeAll callback:

let token = '';

beforeAll(async () => {
  const response = await supertest(app).get('/authentication/test');
  token = response.body.token;
});

Subsequently, utilize the set method to transmit the token in the test scenario:

describe('Simple post test using auth', () => {
  test.only('should return a status code of 200', async () => {
    const response = await supertest(app)
      .post('/tests/simple')
      .set('Authorization', `Bearer ${token}`);

    expect(response.statusCode).toBe(200);
  });
});

Answer ā„–2

I have implemented the following code snippet:

    import * as request from 'supertest';

    describe('Testing a simple POST request with authentication', () => {
    test.only('should return a 200 status code', async () => {
     const res = await request(app.getHttpServer())
      .post('/tests/simple')
      .send(payload)
      .set('Authorization', `Bearer ${token}`);

    expect(res.statusCode).toBe(200);
  });
});

I also recommend mocking your authentication request. You can refer to this stackoverflow question for guidance if you are using Jest: Mock Authentication Request -Jest

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

Utilizing VueJS to Establish a Binding Relationship with Props

One of my Vue components is named Avatar.vue, and it is used to create an avatar image based on user-defined props. The parameter imgType determines whether the image should have rounded corners or not. Here is the code: <template> <div> & ...

Ways to trigger the React component to refresh when it receives an update via a web socket

Looking to enhance a React JS page featuring a dynamic table. Here are the key requirements: Utilize React Table to load and populate the table data by calling the Data API Establish a web socket connection on the client side to receive real-time updates ...

Javascript failing to choose background color from an array

I am attempting to create a subheader with varying colors, similar to the one found on the Ask Different page. However, instead of manually assigning colors, I am looking to have it randomly select a color from a Javascript array. I have already outlined ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Adjusting SVG size based on the position of the cursor for transforming origin

My goal is to scale an SVG circle using the trackpad (by moving two fingers up and down), with the origin of the transform being the cursor position. Initially, the scaling works as intended, but on subsequent attempts, the circle changes position, which s ...

Can you explain the distinction between ajaxComplete and beforesend when making an Ajax call with JavaScript?

Can you explain the usage of ajaxComplete and beforesend? What sets them apart from each other? Are there any alternative methods similar to success when making an Ajax call? ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

Creating an MP3 Text to Speech file with IBM Watson

I have been referring to the documentation for implementing the IBM Watson Text-to-Speech API using Node.JS. My goal is to generate output files in MP3 format. The documentation suggests modifying the base code, but I'm struggling with this. The resu ...

Encountering errors while attempting to render MUI components in jsdom using react testing library within a mocha test

Due to the lack of maintenance and support for React 18+ in enzyme, I am faced with the task of migrating over 1750 unit tests to work with react-testing-library and global-jsdom. This migration is necessary so that our application can continue running on ...

listbox fails to populate in Internet Explorer but functions correctly in Firefox and Chrome

Hey there! Iā€™m currently working with PHP and JavaScript on a code snippet that allows an admin to select a name from a dropdown menu, which then displays the locations associated with that name. These names belong to sales guys. The functionality works ...

Populating a dropdown menu in a form with data from a different model using Node.js

I'm currently working on creating a dropdown list for a form that involves two different models: cars and colours. I'm having trouble figuring out how to populate the dropdown list in the cars.jade file with data from the colours model. The goal ...

Pause and let the previous function complete before initiating a new one

There are 4 Ajax functions in play here. The first one operates independently, while the other three depend on the ones before them. For example, consider a scenario with Country, Governorate, District, Town, and Road. The Country can be accessed directly, ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Problem encountered when bundling Swagger UI Express plugin with webpack for production deployment

Having an issue with the integration of the swagger-ui-express plugin in my node express REST API. When trying to bundle with webpack in production mode, I keep getting an error stating that SwaggerUIBundle is not defined. My app works fine without using w ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

Unable to add an item from an array to the data property in Vue.js

When fetching data from Laravel, I use the following response: $unserialize = unserialize($import->field_names); return response()->json( $unserialize, 200 ) ; On Vue JS, I can view the response using: console.log(response); The data is displayed i ...

In JavaScript, we have an array of objects where each object contains both another array and an integer value

I'm feeling a bit lost on how to tackle this issue and could use some guidance. I've been struggling to find resources on how to load an array that is nested within an Object. The following function is where I've hit a roadblock: function F ...

How to successfully close a jQuery dialog within a user control

My user control has a list view with a hyperlink (LnkDelete) that triggers a jQuery dialog. Here is the javascript code responsible for this functionality: $('#LnkDelete').live('click', function (e) { var page = $(this).at ...

An efficient method for removing a column using JavaScript

Hello, I'm seeking assistance with the following code snippet: $(document).on('click', 'button[id=delete_column]', function () { if (col_number > 1) { $('#column' + col_number).remove(); $('#col ...