Performing Cypress testing involves comparing the token stored in the localStorage with the one saved in the clipboard

I am currently working on a button function that copies the token stored in localStorage to the clipboard. I am trying to write code that will compare the token in localStorage with the one in the clipboard in order to verify if the copy was successful.

Here is my current approach:

cy.get('.copy-to-clipboard').click();
cy.window().its('navigator.clipboard').invoke('readText')
  .should('equal', localStorage.getItem(accessTokenKey));

This method is not providing accurate results and is causing issues for me. Any assistance or alternative solutions would be greatly appreciated.

Answer №1

Perhaps the issue lies in mixing synchronous and asynchronous code.

To resolve this, consider:

cy.get('.copy-to-clipboard')
  .click()
  .then(() => {  // wait for click to finish
    cy.window().its('navigator.clipboard').invoke('readText')  
      .should('equal', localStorage.getItem(accessTokenKey))
  })

Alternatively, you can enable retries for the .should() assertion:

cy.get('.copy-to-clipboard').click()

const accessTokenKey = localStorage.getItem(accessTokenKey)
cy.window().then(win => {
  cy.wrap(win.navigator.clipboard.readText())  // reattempt readText if needed
    .should('equal', accessTokenKey)
})

Answer №2

Regrettably, native copy/paste support is not yet available in Cypress. However, there are a few workarounds to consider:

1. Initial Recommendation

cy.window().then((win) => {
    win.navigator.clipboard.readText().then((text) => {
        expect(text).to.eq('your copied text');
    });
});

2. Alternative Approach:

cy.window().its('navigator.clipboard')
  .invoke('readText').should('equal', 'copied text')

3. Third suggestion, involve clipboardy dependency

To begin, install the dependency: `npm i -D clipboardy``

Incorporate the following code into your plugins/index.js file:

const clipboardy = require('clipboardy');
module.exports = ( on ) => {
    on('task', {
        getClipboard () {
            return clipboardy.readSync();
        }
    });
};

Subsequently, utilize it in your test:

cy.task('getClipboard').should('contain', '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

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Maximizing the potential of mouse positioning in Angular

I am working with an Angular form that has a textarea <textarea class="form-control" id="message" formControlName="message" (fo ...

Ways to verify function arguments within an asynchronous function using Jest

I have a function that needs to be tested export const executeCommand = async ( command: string ): Promise<{ output: string; error: string }> => { let output = ""; let error = ""; const options: exec.ExecOptions = { ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Is there a reason for TypeScript compiler's inability to effectively manage filtering of nested objects?

Perhaps a typical TypeScript question. Let's take a look at this simple filtering code: interface Person { id: number; name?: string; } const people: Person[] = [ { id: 1, name: 'Alice' }, { id: 2 }, { id: 3, name: 'Bob&apos ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...

Tips and tricks for sending data to an angular material 2 dialog

I am utilizing the dialog box feature of Angular Material2. My goal is to send data to the component that opens within the dialog. This is how I trigger the dialog box when a button is clicked: let dialogRef = this.dialog.open(DialogComponent, { ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

Determining Refresh Status in Angular Application

Does Angular provide a method to determine if the browser has been refreshed? I need to verify whether the page has been refreshed or not, as I want to run a function only when the value is false. In my ngOnInit function, I have the following code: pageIs ...

Clicking on an element- how can I find the nearest element?

Encountering an issue with my next js app where I am attempting to assign a class to an element upon clicking a button. The problem arises when trying to access the next div using the following code snippet: console.log(e.target.closest('.request_quot ...

Encountering a npm lifecycle error upon restarting

I recently started learning Angular 2 using Visual Studio Code as my IDE. Initially, everything worked fine when I executed "npm start" for the first time. However, I encountered an error when I tried to stop the process with CTRL+C and then re-executed "n ...

Applause tally problem in Ionic3

For my university project, I am utilizing Ionic-3 and attempting to achieve a similar effect as shown in this example. Please take a look at my code on StackBlitz. I am encountering an issue where I want the count circle to move from the bottom to the top ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Querying multiple attributes in express-restify-mongoose

Issue: I am attempting to send a query from my Angular2 frontend to my Node.js server using express-restify-mongoose. The goal is to search for data based on multiple attributes, instead of just one. Current Working Solution: let regex = '{"title": ...

Encountering "module not found" errors while working on an Angular 2 project using the angular2-seed starter pack

Recently, I upgraded to the latest version and integrated SASS according to the guidelines provided here: https://github.com/mgechev/angular2-seed/wiki/Enabling-SASS-support However, upon running npm start, I encountered a series of errors: [18:07:51] & ...

Leveraging Angular environment configurations for workspace libraries

I've been experimenting with Angular's latest version (>6) and am delving into the concept of using workspaces. One interesting feature is the ability to generate a library project with a simple CLI command: ng generate library api In my de ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...