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

Encountered a problem while trying to install angular-cli on a Windows 10

While attempting to set up angular-cli on my Windows 10 device, I used npm install -g @angular/cli. However, an error popped up as follows: C:\Users\kumar>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near &a ...

What is the reason for the lack of compatibility between the TypeScript compilerOptions settings 'noEmitOnError: true' and 'isolatedModules: false'?

Whenever I try to execute TypeScript with isolatedModules set as true and then false, I keep encountering this error message: tsconfig.json(5,9): error TS5053: Option 'noEmitOnError' cannot be specified with option 'isolatedModules'. ...

The problem of package related to scrolling header in Ionic arises when building with the `--prod` flag (Remember to include a @NgModule annotation

Hey there! I stumbled upon a package in the git repository that seems to have everything set up for compatibility with AOT. However, when attempting to build my app using the ionic build --prod command, the AOT build encounters an error as displayed below. ...

Problems with Angular 14 and NGRX Selector causing complications

At my basket store, I currently have 5 items with 2 of them having an id of 4. https://i.stack.imgur.com/YIplp.png In my reducer, when I use: on(getBasket, (state, { id }) => state.filter((photo) => photo.id !== id) It works to remove the item fr ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

What could be causing this particular issue when using the Firestore get() method? The error message states: "ERROR TypeError: snaps

In my current Angular project, I am utilizing Firebase Firestore database and have implemented the following method to execute a query: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsAppliedByCurrent ...

What could be the reason for Angular to merge the element at index 0 of an array into a subarray instead of doing

After setting up the Array in my oninit function, I encountered an issue where one part of the array was functioning as intended while the other returned an error. this.tests = [{ status: 0, testresults: [{ name: 'test ...

Transforming the data type of a variable

Recently, I decided to switch my file name from index.js to index.ts. Here's an example of the issue I'm facing: let response = "none" let condition = true if(condition){ response = {id: 123 , data: []} } console.log(response) Howev ...

Develop a module using the Angular plugin within the Eclipse IDE

I am currently new to Angular and following the Angular Get Started Tutorial (https://angular.io/guide/quickstart). I am using the angular cli plugin in Eclipse. As I reached the 7th part of the tutorial, I am required to create a new module with the comm ...

TypeScript perplexed Babel with its unfamiliar syntax and could not compile it

Encountered a problem while attempting to compile typescript. It appears that babel was unable to comprehend the "?." syntax on the line node.current?.contains(event.target) export function useOnClickOutside(node: any, handler: any) { const handlerRef = ...

What is the best way to transform an array containing double sets of brackets into a single set of brackets?

Is there a way to change the format of this list [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]] to look like [" ", " ", " &qu ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

The error message "The element 'router-outlet' is unrecognized during the execution of ng build --prod" appears

I encountered a specific error message when running ng build --prod, although the regular ng build command works without issue. Error: src/app/app.component.html:1:1 - error NG8001: 'router-outlet' is not recognized as an element: 1. If 'rou ...

Exploring the various form types supported by 'react-hook-form'

I utilized react hooks form to create this form: import React from "react"; import ReactDOM from "react-dom"; import { useForm, SubmitHandler } from "react-hook-form"; import "./styles.css"; function App() { type ...