Using Cypress and JWT, automate the login process for JHipster

Is there a way to automate the bypassing of the JHipster login screen?

This is my goal:

let jwt_token

before(function fetchUser() {
    cy.request('POST', '/api/authenticate', {
        username: 'user',
        password: 'user',
    })
        .its('body')
        .then((res) => {
            jwt_token = res.id_token
        })
})

beforeEach(function setUser() {
    cy.visit('/', {
        onBeforeLoad(win) {
            win.sessionStorage.setItem('jhi-authenticationtoken', jwt_token);
            win.localStorage.setItem('jhi-authenticationtoken', jwt_token);
        }
    })
})

describe('test', () => {
    it('verify programmatically if login works', () => {
        cy.log(jwt_token);
        cy.visit('/');
        cy.get('.lead').should('have.text', 'Here is microservices catalog');
        cy.get('#home-logged-message').should('have.text', 'You are logged in as user "user".');
    })
})

Although jwt_token appears to have the correct value, the login process is still not successful and the 'test' fails.

Has anyone had success with this before?

Answer №1

One useful trick is to enclose the token itself in quotation marks. For example, here's how you can authenticate within your JHipster application when using JWT:

function loginUser(username: string, password: string): void {
  cy.request('POST', '/api/authenticate', {
    username: username,
    password: password
  })
    .its('body')
    .then((res) => {
      window.sessionStorage.setItem('jhi-authenticationtoken', '"' + res.id_token + '"');
    })
}

You can view a live demonstration here

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

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

Develop a structured type that encompasses the stationary attributes of an object-oriented class

Provided are the following classes: class EnumerationDTO { designation: string; id: number; } class ExecutionStatusDTO extends EnumerationDTO { static readonly open: ExecutionStatusDTO = { id: 0, designation: 'Open' }; static readonl ...

Three.js - spinning texture applied to spherical shape

Would it be possible to rotate a loaded texture on a sphere geometry in Three.js without rotating the object itself? I am seeking a way to rotate just the texture applied to the material. Imagine starting with a sphere like this: https://i.sstatic.net/Ol3y ...

Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this co ...

Retrieve the object from the data received from the HTTP GET API call

I have a question that has been asked before, but I am unable to achieve the desired result with my current approach. When my service retrieves data from an API, it returns results in the following format: { "nhits": 581, "paramete ...

Incorporate Font Awesome icons throughout your Angular8 application for added visual appeal

I'm currently working on a large Angular application that utilizes lazy loading modules. Throughout various components in different modules, I make use of icons from Font Awesome individually. Here is an example: In component.ts: import { faChevronD ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

Transmit a form containing a downloaded file through an HTTP request

I am facing an issue with sending an email form and an input file to my server. Despite no errors in the console, I can't seem to upload the file correctly as an attachment in the email. post(f: NgForm) { const email = f.value; const headers = ...

Prevent using keys of nullable properties as method parameters in Typescript generics

What is the solution to disallow a method from accepting a parameter of type keyof this where the property is nullable? Consider the following example: abstract class MyAbstractClass { get<K extends keyof this>(key: K): this[K] { return this[k ...

How come the variable `T` has been assigned two distinct types?

Consider the following code snippet: function test<T extends unknown[]>(source: [...T], b: T) { return b; } const arg = [1, 'hello', { a: 1 }] const res = test(arg, []) const res1 = test([1, 'hello', { a: 1 }], []) The variabl ...

Sign up for the identical Observable within a Child Component in Angular 2 using TypeScript

This question may seem simple, but as a newcomer to Angular 2, I often find myself needing more explanation despite the good examples and tutorials available. Within a component, I have an observable that gets updated periodically. While I've simplif ...

Ways to showcase information retrieved from an API onto an Angular Material card

The process involves calling two different APIs. The first API gathers user information such as name, ID, and the IDs of applications where the user is registered. The second API retrieves details from each application based on its ID. Despite successfully ...

The performance of ternary operators in Typescript-based Reactjs fell short of my expectations

As a newcomer to TypeScript+ReactJS, I am facing an issue with the Ternary operator in my code. Here is the code snippet: import React, { SyntheticEvent,useRef,useState } from "react"; import Result from './Result'; //main application c ...

experimenting with asynchronous promises in Jasmine to test Angular 2 services

Currently, I'm facing some challenges while testing my Angular 2 service. Even though my tests are passing, I keep encountering this error in the console: context.js:243 Unhandled Promise rejection: 'expect' was used when there was no c ...

Angular2 - error in long-stack-trace-zone.js at line 106: Zone variable is not defined

Currently, I am utilizing the Angular2 starter with webpackjs AMD. While there are no build errors showing up, I encounter some issues when browsing (using npm server), resulting in the following errors: What aspects might I be overlooking in my build con ...

After the "markerClick" event triggers in Angular2 SebmGoogleMapMarker, the view fails to update

I am dealing with an array structured like this: locations: marker[] = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)', iconUrl: 'img/marker.png'}, {id: '2&apos ...

Adding properties to request object on-the-fly - Google Pay [Typescript]

Here is how I am constructing the payment request object: paymentRequestObject: google.payments.api.PaymentDataRequest = { apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [ { type: 'CARD', parameters: { allowedAuthMethod ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...