DEV Community

Tyler Smith
Tyler Smith

Posted on

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.

Top comments (0)