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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay