DEV Community

Tyler Smith
Tyler Smith

Posted on

1

Programmatically generate files in Cypress tests

The Cypress documentation recommends using fixtures for file uploads, but cluttering up a repository with fixture files can feel gross. Ideally, the test suite could programmatically generate files on the fly that match the needs of a particular test.

You can use Cypress's selectFile method and a Blob to create file testing stubs that don't require an underlying fixture.

cy.get('[data-testid="file-input"]').selectFile({
  contents: Cypress.Blob.createBlob([]),
  fileName: "picture.png",
  mimeType: "image/png",
  lastModified: Date.now(),
});
Enter fullscreen mode Exit fullscreen mode

This code stubs out a basic file that can be used by a file input. The only property that Cypress requires is contents, but the other properties can be used on an as-needed basis. For example, the mimeType can be used if the input field has an accept attribute, and the browser will use the mimeType from the stub and behave accordingly.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more