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

What is the reason for the countdown number's color remaining the same even after it reaches a specific time threshold?

Creating a simple countdown for sports was my idea, but now I'm stuck on the "changeColor" part that I don't have enough knowledge about. The countdown is functioning perfectly, but customizing the colors and adding CSS animations seems challeng ...

Ways to avoid submitting based on the outcome of AJAX requests

When working on an ASP.NET MVC Project, I encountered an issue where I wanted to prevent a button from submitting if the result returned from an AJAX call was false. However, no matter what I tried, the button always triggered the submission. Below is th ...

Tips for managing modal closure when the InertiaJS form succeeds?

Hello everyone! Currently, I'm involved in a Laravel project where I am using laravel/breeze VueJS with Inertia. The login functionality is implemented using a bootstrap modal component. While validation and authentication are working smoothly, the on ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

Using Vue.js to create numerous modal popups

Currently, I am using Vue.JS for a research project at my workplace. My focus right now is mainly on the front-end. I have a table with several entries, and when a row is clicked, I want a modal popup window to display further details about that specific ...

Implementing pagination links to trigger image changes on click

I have a javascript function that swaps the image source when clicked. I am looking to incorporate pagination links in this script. Specifically, I want to include "Previous" and "Next" text links to navigate between images. Can someone help me figure out ...

Anticipated the server's HTML to have a corresponding "a" tag within it

Recently encountering an error in my React and Next.js code, but struggling to pinpoint its origin. Expected server HTML to contain a matching "a" element within the component stack. "a" "p" "a" I suspect it may be originating from this section of my c ...

Is it possible to export CSS stylesheets for shadow DOM using @vanilla-extract/css?

I have been exploring the use of @vanilla-extract/css for styling in my React app. The style method in this library exports a className from the *.css.ts file, but I need inline styling to achieve Shadow DOM encapsulation. During my research, I came acros ...

The initial render of Keen-slider in NextJS can sometimes encounter difficulties when using server-side rendering

While incorporating the keen-slider library v5.4.0 into my nextJS project with TypeScript, I encountered a peculiar issue. The error arises when the keen-slider is initially loaded for the first time, resulting in mismatched transform types causing items ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

I am able to input data into other fields in mongoDB, however, I am unable to input the

I am facing an issue with the password while everything else seems to be working fine. I am using a schema and getting an error, but it could be a problem in my functions because I hashed the password. I am unable to identify what's causing the issue. ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...

Having Trouble with QR Code Generator Functionality

UPDATE: The initial code has been updated to implement the recommendations provided. I am currently working on a QR Code generator that updates every minute. Although I have developed the code below, I am encountering some errors and could use some assist ...

JavaScript and CSS animations offer dynamic and engaging ways to bring

I'm working on a div section and I want it to come down and rotate when a button is clicked. However, after moving to the bottom, it doesn't rotate as expected but instead returns to its initial position along the Y axis. How can I fix this issue ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...