Passing data between API tests in JavaScript

I'm encountering an issue where I need to create e2e api tests. The goal of the first test is to obtain a token for an unauthorized user, use that token in the method header for the second test to return a token for an authorized user, and then continue using that second token in subsequent tests. How can I store the token values in variables and pass them through the tests?

As a newcomer to JS, I am now facing a 'ReferenceError: auth_token is not defined'.

const chai = require('chai');
const request = require('request-promise-native');
const mocha = require('mocha');
const config = require('../config');

const assert = chai.assert;

describe('0_auth', () => {
  it('should return token for unauthorized user', async () => {
  const result = await request({
  headers: config.headers,
  url: `${config.url}/rest/v1/auth/get-token`,
  method: "POST",
  json: {
      "deviceUuidSource": "DEVICE",
      "source" : "KIOSK",
      "deviceUuid" : "uniquedeviceuuid"
  }
});
   assert.isNotNull(result);
   assert.property(result, 'token');
   var auth_token=result.token;
   console.log(auth_token)
   }).timeout(15000);


 it('should return token for authorized user', async () => {
 const result = await request({
  headers: Object.assign(config.headers, { 'Authorization': 'Bearer '+auth_token }),
  url: `${config.url}/rest/v1/auth/with-password`,
  method: "POST",
  json: {
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1672637a736e6378257e6061265627267b7f7886623c6e6f64">[email protected]</a>",
    "password" : "Test123"
     }
   });
   assert.isNotNull(result);
   assert.property(result, 'token');
   assert.property(result, 'user');
   console.log('token:', result.token);
 }).timeout(15000);
 });

For the following test, I plan to pass the Bearer token to the Authorization field in a different class called config.js

config.headers = {

 'User-Agent': 'WOR API Tester', // android
  Source: 'MOBILE',
 'Accept-Language': 'EN',
 Authorization:'Bearer '+auth_token;


};
module.exports = config;

Answer №1

Got the bearer for the next test working now, but I have a question.

Why is the bearer saved in auth_token working in other test classes but not in the class below? Here we see this line:

headers: Object.assign(config.headers, { 'Authorization': 'Bearer '+auth_token }),

In other classes, I only have the following line:

headers: config.headers,

And there's no mention of using auth_token in authorization; in config.js, there's also no mention of a token.

const chai = require('chai');
const request = require('request-promise-native');
const mocha = require('mocha');
const config = require('../config');

const assert = chai.assert;

describe('0_auth', () => {
  var auth_token = ''
  it('should return token for unauthorized user', async () => {

const result = await request({
  headers: config.headers,
  url: `${config.url}/rest/v1/auth/get-token`,
  method: "POST",
  json: {
      "deviceUuidSource": "DEVICE",
      "source" : "KIOSK",
      "deviceUuid" : "uniquedeviceuuid"
     }
   });
   assert.isNotNull(result);
   assert.property(result, 'token');
   auth_token=result.token;
}).timeout(15000);


 it('should return token for authorized user', async () => {
const result = await request({
  headers: Object.assign(config.headers, { 'Authorization': 'Bearer '+auth_token }),
  url: `${config.url}/rest/v1/auth/with-password`,
  method: "POST",
  json: {
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c584950594449520f544a4b0c7c0d0c515552494812444546">[email protected]</a>",
    "password" : "Test123"
     }
   });
assert.isNotNull(result);
assert.property(result, 'token');
assert.property(result, 'user');
 }).timeout(15000);
 });

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

Successful Ajax response notification

I am new to using ajax and I want to implement a .post method with an if condition to notify the user of its success or failure. Here is my code for .post: $.post("ajaxRegistering.php",{ name: name, lastname: lastname, ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Competition among fetch requests

I am currently developing a tracker that is designed to gather data from our clients' websites and send it to our API using fetch requests when site users navigate away from the page. Initially, I planned to utilize the beforeunload event handler to ...

How to link AngularJS controller from a different module in routing

My current project involves creating a complex app with a structured design: Each module is organized in its own folder structure, including controllers, directives, and more. Within each folder, there is an index.js file along with other files for separ ...

Tips for updating process.version in a Node.js environment

After upgrading my node version from v3 to v11 using nvm with the command nvm use 11.12.0, I noticed that when I check the version using node -v in the terminal, it correctly shows 11.12.0. I also have a node js application that is started through pm2. I ...

What is the best way to halt Keyframe Animation once users have logged in?

To enhance user engagement, I incorporated keyframe animation into my login icon on the website. The main objective is to capture the attention of visitors who are not registered users. However, once a user logs in, I intend for the keyframe animation to c ...

Exploring the beauty of ASCII art on a webpage

Having trouble displaying ASCII art on my website using a JavaScript function, the output is not as expected... This is how it should appear: And here is the code I am trying to implement for this purpose: function log( text ) { $log = $('#log&ap ...

Maven profile not executing specified tests

Within my Maven pom file, I have set up a simple profile to execute some integration tests during the default test phase rather than the integration-test phase. The reason for this is that I want to avoid building and deploying the war file. These tests ar ...

Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success. Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of re ...

Discover identical HTML elements

I have a simple HTML code that I would like to split into similar parts: <input id="checkbox1"><label><br> <input id="checkbox2"><label><br> <input id="checkbox3"><label><br> The desired result should ...

How can I deliver assets in React without the PUBLIC_URL showing up in the path?

I have set up a portfolio website that includes my resume. I am trying to make it so that when someone visits the route http://localhost:3000/resume.pdf, they can view my resume directly. The resume.pdf file is located in my public folder. However, instead ...

Importing modules dynamically in NextJS allows for the loading of

I have a basic function that is responsible for loading a script: const creditCardScript = ( onReadyCB, onErrorCB, ) => { let script = document.createElement("script"); script.type = "text/javascript"; script.src = process.CREDIT_CARD_SCRIPT; ...

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Creating a distinct header value for every $http request

I've been assigned the task of adding a unique ID for each request to all HTTP requests made by our AngularJS application for logging purposes. While this is more crucial for API calls, I'm currently working on implementing it for all kinds of re ...

Switchable radio options

Currently, I am creating a form containing multiple options that are mutually exclusive. However, none of these options are mandatory. That is why I want to enable the user to uncheck a selected radio button by simply clicking on it again. This way, all th ...

How to display a div in Angular when hovering with ElementRef and Query List

I am having trouble implementing a ngFor loop in my project where I want to display a div on mouse hover using the @Input notation. This is how my HTML code looks: <div class="col s12 m6" style="position: relative" *ngFor="let res of hostInfo.resident ...

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...