Thakgrandka
Thakgrandka

Reputation: 524

cypress retrieve JWToken and set as header for further requests

When trying to test a express webapplication i build the test should first authenticate to retrieve a JWT token, the token retrieving works but the method to set the header for further requests doesn't work.

This code creates the method to run when authentication is needed,

Cypress.Commands.add("userRequest", function(requestObj) {

    // Make a login request, returning a JWT token
    cy.request({
        method: 'POST', 
        url: '/credentials',
        body: {
            "name": "test_user",
            "password": "test123_"
        }
    }).then(function(response) {
        requestObj.headers = requestObj.headers || {};
        requestObj.headers.Authentication = response.body.token;

        return cy.request(requestObj);
    });

This is the code that runs

it('retrieves one user', function () {
        cy.userRequest(cy.request({
            url: '/users/1'
        })).then(function (response) {
            expect(response.body.name).to.equal("admin");
        });
    });

BUT when the test runs the console tells me

CypressError: cy.request() failed on:

http://localhost:3000/users/1

The response we received from your web server was:

401: Unauthorized

This was considered a failure because the status code was not '2xx' or '3xx'.

Can anyone help me?

thanks in advance!

Upvotes: 2

Views: 1646

Answers (1)

Prany
Prany

Reputation: 2143

As I said in my comment that cypress works on async programming, so try with in support/command.js

Cypress.Commands.add('userRequest', (email, password) => {
Cypress.log({
  name: 'loginViaAuth0',
});
    const options = {
    method: 'POST',
    url: '/credentials',   
   "body":'userName='+email+'&Password='+password+'
  };
  cy.request(options)

});

Then in your code

cy.userRequest(userName,password)
  .its('body').then((response)=>{

  // Do your stuffs

 })

Upvotes: 3

Related Questions