Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far:

Cypress.Commands.add('upload_image', (fileName, selector) => {
  return cy.get(selector).then(subject => {
    return cy.fixture(fileName, 'base64')
      .then(Cypress.Blob.base64StringToBlob)
      .then(blob => {
        const el = subject[0]
        const testFile = new File([blob], fileName, { type: 'image/png' })
        const dataTransfer = new DataTransfer()
        dataTransfer.items.add(testFile)
        el.files = dataTransfer.files
        return subject;
      })
  })
})

When calling this in my test as shown below:

 cy.upload_image("logo.png", ".jss378");

No errors are thrown, but unfortunately nothing gets uploaded. It's worth noting that the selector (.jss378) is dynamic, and I am seeking a non-dynamic solution.

Below is an extract of my HTML code: view image description here

Answer №1

Successfully resolved the issue by utilizing the cypress upload plugin

These are the steps I took:

1) Inserted the following code in the command.js file:

import 'cypress-file-upload';

2) Utilized the code below in the test script:

// uploading the brand logo
    const fileName = 'logo.png';

cy.fixture(fileName).then(fileContent => {
  cy.get('[title="Logo"]').upload(
    { fileContent, fileName, mimeType: 'image/png' },
    { subjectType: 'drag-n-drop' },
  );
});

For more details, refer to the documentation: https://docs.cypress.io/plugins/index.html#content

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

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

Understanding the Functions of Angular Providers and Implementing Them

Just starting out with Angular and following a tutorial from this video. I decided to experiment by adding providers :[EmployeeService] to both employee-list.component.ts and empployee.component.ts within the @component section. However, this led to an err ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...

The componentWillReceiveProps method is not triggered when a property is removed from an object prop

Just starting out with React, so I could really use some assistance from the community! I am working with a prop called 'sampleProp' which is defined as follows: sampleProp = {key:0, value:[]} When I click a button, I am trying to remo ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

Learn how to configure gulp-typescript to automatically generate individual JavaScript files for each TypeScript file within the same directory

My interest lies in utilizing the gulp-typescript module for handling typescript compilation. My goal is to set up a configuration where each typescript file translates into one javascript file in the corresponding directory, similar to how it works with t ...

Incorporate a background image into mat-dialog

I've been struggling to set a background image on my mat-dialog, but for some reason it's not showing up at all. I attempted using a panelClass as well, but still no luck. .custom-panel .mat-dialog-container { background-image: url("../. ...

Encountering error TS2304: Cannot resolve name 'classes' when attempting to apply styling in React using Typescript

I'm having trouble customizing the styles on my website, specifically when trying to add a custom className. Error Message: Cannot find name 'classes'. TS2304 Below is the code I am currently working with: import React from 'react& ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...

The header component does not update properly post-login

I am currently developing a web-app using Angular 8. Within my app, I have a header and login page. My goal is to update the header after a user logs in to display information about the current logged-in user. I attempted to achieve this using a BehaviorS ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Cannot execute loop

I'm currently working on creating a loop within my component that involves making server calls: getBeds() { this.patientService.getBeds(this.selectedWard).subscribe( result => { console.log(result); this.beds = result; this.getBedDet ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Automatically arrange TypeScript import statements in alphabetical order in WebStorm / PhpStorm

I am using tslint with the default config tslint:recommended and I am looking to minimize the number of rules I need to customize. Some rules require that imports be alphabetized: src/core/task/TaskMockDecorator.ts[2, 1]: Imports within a group must be a ...