Unable to transfer token to a different file within cypress

I'm encountering an issue where I make an API request to get a token and try to use it in another function located in a separate file. However, when I export the token from one file to another, it does not work as expected. The 'activate user' method is unable to read the token.

Here is my code in one file:


class User {
  user_T= ''

  getaccessToken(){
    cy.request({
        method: 'POST',
        url: 'url',
        form: true,
        body: {
          "username": ...,
          "password": ....
        }
      })
      .then(response => {
          return this.user_T = response.body.Token;
      })
  }
}

export default new User

The other file contains:


import User from './user'

const token= new User()

it.only('activate user', () => {
    cy.request({
      method: "POST",
      url: 'url/activate',
      headers: {
        'Authorization' : 'Bearer ' + token.user_T,
      },
      body:{
       "test": 'test'
      } 
    }) 
})

Answer №1

  1. It is unnecessary to both set and return
    this.user_T = response.body.Token;
    within your .then() block. Choose either one based on your requirements. Setting the value directly or returning it for assignment are valid options, but combining them is not recommended.
.then((response) => {
  this.user_T = response.access.Token
});
// or
.then((response) => {
  return response.access.Token
});

If you opt to return the value from the .then(), make sure to return the entire chain of cy.request() command.

  1. getaccessToken is responsible for generating a non-empty string value for user_T. To ensure user_T is not empty, call this function.
// Assuming you are still setting the `user_T` value instead of returning it
import User from './user'

const user = new User()

it.only('activate user', () => {
  user.getaccessToken().then(() => {
    cy.request({
      
      method: "POST",
      url: 'url/activate',
      headers: {
        'Authorization' : 'Bearer ' + user.user_T,
    },
      body:{
       "test": 'test'
      } 
    }) 
  })
})

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

Steps for setting up a nested route in Angular 2

I am currently working on a project that includes an admin page (check the file structure below). I am trying to set up a child route named 'createuser' for the admin page (localhost:4200/admin/createuser). Despite my attempts, I encountered an e ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

What is the method for adding a leading '+' sign to positive numbers using Intl.NumberFormat?

I'm currently utilizing Intl.NumberFormat in TypeScript/JavaScript within Angular2 to convert a numeric type into a formatted string. While this method is ideal, I am in need of a solution that would include a leading plus sign for positive numbers. ...

An error occurred due to attempting to access properties of null while trying to read 'useMemo' in a Next.js TypeScript application

Currently engaged in a Next.js 13 project with TypeScript, utilizing the useDrag hook. No errors are being flagged in my Visual Studio Code editor; however, upon attempting to render the page, an error message surfaces. The issue points to a problem with t ...

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

issue encountered when initializing a variable in C++

I'm currently working on some code that involves arrays, but I keep encountering an error message that says "variable sized object may not be initialized" for the variables in the array, even though I'm initializing them as 0 in the lines precedi ...

Using Angular 2's ngModel directive to bind a value passed in from an

Using [(ngModel)] in my child component with a string passed from the parent via @Input() is causing some issues. Although the string is successfully passed from the parent to the child, any changes made to it within the child component do not reflect bac ...

What could be causing my code to not run after subscribing to the observables?

In my code, I have two methods that return two lists: one for accepted users and the other for favorite users. The first part of my code works well and returns both lists, but in the second part, I need to filter out the accepted users who are also on the ...

Searching through a Postgres JSONB column, you can select specific elements from an array by using wildcards

I am exploring the use of jsonb columns with arrays in PostgreSQL and want to filter data based on them. Here is an example schema with a column: CREATE TABLE testtable ( id varchar(32) NOT NULL, refs jsonb NULL, ) The 'refs' c ...

Stop PHP array processing when a column surpasses a certain threshold

As a non-coder, I attempted to modify a code that was originally created by a developer I hired in 2018. However, the lack of coding knowledge is proving to be quite challenging for me. My goal here is to have this code generate another table if the initia ...

The element ''ag-grid-angular'' is unrecognized:

After using ag-grid successfully for a few months, I attempted to integrate a grid from a previous project into an Angular template like the one found in ngx-admin: ngx-admin This is how the template is structured: https://i.sstatic.net/Mfjw8.png I tr ...

Tips for releasing a TypeScript npm package with embedded CSS modules?

Currently, I am developing a TypeScript-based library in-house for shared React components. The build process is straightforward - simply using tsc and then publishing to our internal npm registry. We don't need a complex Babel compilation process bec ...

Angular 2 Table Serial Number

I have data coming in from an API and I want to display it in a table. In the table, there is a column for serial numbers (#). Currently, I am able to show the serial numbers starting from 1 on every page. However, when I switch pages, the counting starts ...

Issue with Vue.js: v-for loop not properly cycling through array to generate list items

I am experiencing some difficulties with my v-for loop that is intended to generate a list based on the length of an array. Despite thinking it was a simple task, I am struggling to identify where I made a mistake. The loop only seems to display the first ...

Receiving integer input from a user and adding it to an array in Java

Currently, I am facing an issue when attempting to compare the maximum number in an array. An error, java.lang.ArrayIndexOutOfBoundsException, occurs whenever I try to insert a value larger than 5 into the array. Below is the code I am working with: impo ...

Converting an array into a tree structure in Perl or exploring the issue of arbitrary variable changes

Converting the given structure in Perl - even elements are "parents" and odd are "childrens: $VAR1 = 'ng1'; $VAR2 = [ 'ng1_1', 'ng1_2', 'ng1_3', 'ng1_4' ]; $ ...

Typescript: Mastering the Art of Uniting Diverse Types

I'm in the process of developing a React application using Typescript. One of my components is responsible for fetching user data from the server (I'm using firebase), and then storing this data in the component's state. // Defining a cus ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Can you explain the distinction, if one exists, between a field value and a property within the context of TypeScript and Angular?

For this example, I am exploring two scenarios of a service that exposes an observable named test$. One case utilizes a getter to access the observable, while the other makes it available as a public field. Do these approaches have any practical distincti ...