Skip to main content
Cypress App

readFile

cy.readFile() reads a file from disk and yields its contents. It reads the file again until the file exists and your assertions pass, so it suits files that change during a test, such as downloads, logs, and files your app generates. For test data that stays the same, use cy.fixture(), which reads the file once and caches it.

Syntax​

cy.readFile(filePath)
cy.readFile(filePath, encoding)
cy.readFile(filePath, options)
cy.readFile(filePath, encoding, options)

Usage​

Correct Usage

cy.readFile('menu.json')

Arguments​

filePath (String)

A path to a file, resolved relative to the project root (the directory that contains the Cypress configuration file). An absolute path also works.

encoding (String)

The encoding to use when reading the file. Defaults to 'utf8'. The following encodings are supported:

  • 'ascii'
  • 'base64'
  • 'binary'
  • 'hex'
  • 'latin1'
  • 'utf8'
  • 'utf-8'
  • 'ucs2'
  • 'ucs-2'
  • 'utf16le'
  • 'utf-16le'
  • null

Passing null yields the file as a Cypress.Buffer instance, regardless of file extension.

options (Object)

Pass in an options object to change the default behavior of cy.readFile().

OptionDefaultDescription
encoding'utf8'The encoding to use when reading the file. Ignored when you pass encoding as the second argument instead.
logtrueDisplays the command in the Command Log
timeoutdefaultCommandTimeoutTime to wait for cy.readFile() to resolve before timing out

Yields ​

  • cy.readFile() yields the contents of the file. It parses a file with a .json extension into JavaScript, unless the encoding is null.
  • cy.readFile() reads the file from disk again if any upcoming command (such as an assertion) in the chain fails.

Examples​

Text​

Read a .txt file​

For any file without a .json extension, cy.readFile() yields the contents of the file as a string.

path/to/message.txt
Hello World
spec.cy.js
cy.readFile('path/to/message.txt').should('eq', 'Hello World')

JSON​

For a file with a .json extension, cy.readFile() parses the contents into JavaScript and yields the result.

path/to/data.json
{
"name": "Eliza",
"email": "eliza@example.com"
}
spec.cy.js
cy.readFile('path/to/data.json').its('name').should('eq', 'Eliza')

Type a JSON file's contents in TypeScript​

Pass a type argument to tell TypeScript the shape of the yielded contents.

spec.cy.js
cy.readFile('path/to/data.json').its('email').should('include', '@')

YAML​

Get translation data from a YAML file​

cy.readFile() yields a YAML file as a string. Parse it with a YAML library, such as js-yaml.

languages/en.yml
sidebar:
- Getting Started
- API
spec.cy.js
const yaml = require('js-yaml')

cy.readFile('languages/en.yml').then((str) => {
// parse the YAML string into an object
const english = yaml.load(str)

cy.get('#sidebar')
.find('.sidebar-title')
.each(($el, i) => {
const englishTitle = english.sidebar[i]

expect($el.text()).to.eq(englishTitle)
})
})

Read files your app or server creates​

Wait for a file download and check its contents​

cy.readFile() retries until the file exists, so it waits for the downloaded file to appear. Build the path from the downloadsFolder configuration.

cy.get('[data-cy="export-csv"]').click()
cy.readFile(`${Cypress.config('downloadsFolder')}/report.csv`).should(
'contain',
'Order ID'
)

Check a log file your server writes during a test​

Read a file that your app or server writes as a side effect, such as a log. cy.readFile() reads the file again until the assertion passes.

// clicking "Save" makes the server append to logs/audit.log
cy.get('[data-cy="save-settings"]').click()
cy.readFile('logs/audit.log').should('contain', 'settings updated')

Encoding​

Specify the encoding with the second argument​

cy.readFile('path/to/logo.png', 'base64').then((logo) => {
// logo is encoded as base64
// and looks something like this:
// aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
})

Specify the encoding in the options object​

Pass encoding alongside other options, such as a longer timeout.

cy.readFile('path/to/logo.png', { encoding: 'base64', timeout: 10000 }).should(
'match',
/^iVBOR/ // base64 for the PNG signature
)

Read a file as a Buffer with null encoding​

cy.readFile('path/to/logo.png', null).then((logo) => {
// logo is read as a buffer
// and looks something like this:
// Buffer([0, 0, ...])
})

Read a .json file as raw text without parsing it​

To check the exact text of a .json file, such as its indentation, read it with null encoding and convert the Buffer to a string. cy.readFile() doesn't parse a file read this way.

cy.readFile('path/to/data.json', null).then((buf) => {
expect(buf.toString()).to.include('"name": "Eliza"')
})

Play an MP3 file from its base64 contents​

cy.readFile('audio/sound.mp3', 'base64').then((mp3) => {
const uri = 'data:audio/mp3;base64,' + mp3
const audio = new Audio(uri)

audio.play()
})

Reuse file contents in file uploads​

Upload a file to an input with .selectFile()​

Alias the contents of a file, then pass the alias to .selectFile(). cy.readFile() stores the file name with the alias, so the upload keeps the original name.

cy.readFile('path/to/logo.png', null).as('logo')
cy.get('input[type=file]').selectFile('@logo')

Notes​

Existence​

Default file existence assertion​

By default, cy.readFile() asserts that the file exists and fails if it does not. It retries reading the file until the file exists or the command times out.

// fails after the defaultCommandTimeout is reached
cy.readFile('does-not-exist.yaml')

The error shows the full path cy.readFile() resolved the file to, so you can check where Cypress looked for it.

Command Log error for cy.readFile('does-not-exist.yaml') saying the file does not exist, followed by the full resolved path /home/user/my-app/does-not-exist.yaml

cy.readFile() retries only when the file is missing. Any other error while reading, such as a .json file that contains invalid JSON, fails the command immediately.

Asserting file non-existence​

Assert that a file does not exist with .should('not.exist').

// passes if the file does not exist
cy.readFile('does-not-exist.yaml').should('not.exist')

Read a file that might not exist​

To read a file that may not exist without failing the test, use cy.task() to read a file that might not exist instead.

Retries​

Automatic retries​

cy.readFile() reads the file again until it passes all of its assertions.

// if this assertion fails, cy.readFile() reads the file again
// until it passes its assertions (or times out)
cy.readFile('some/nested/path/story.txt').should('eq', 'Once upon a time...')

cy.readFile() is a query, so it reads the file again until all chained queries pass, not only assertions.

// retries until the JSON file has a `users[123].name` field and
// the assertion passes
cy.readFile('users.json').its('users.123.name').should('eq', 'John Doe')

How cy.readFile() differs from cy.fixture()​

This table compares the two commands. For when to reach for a static import or cy.task() instead of either one, see Choosing how to load test data in Cypress.

cy.fixture()cy.readFile()
Path is relative tofixturesFolderThe project root
File extensionOptionalRequired
Reads from diskOnce per path and encoding, then yields the cached copyOn every call
Retries until assertions passNoYes, reading the file again on each retry
Images by defaultA base64 stringA utf8 string
Default timeoutresponseTimeoutdefaultCommandTimeout
Command LogNot loggedLogged
Missing fileAlways failsCan be asserted with .should('not.exist')

Rules​

Requirements ​

  • cy.readFile() requires being chained off of cy.
  • cy.readFile() requires the file to exist, unless you assert that it does not with .should('not.exist').
  • cy.readFile() requires the file be successfully read from disk.

Assertions ​

  • cy.readFile() automatically retries until all chained assertions pass.

Timeouts ​

  • cy.readFile() can time out waiting for assertions you've added to pass.
  • cy.readFile() can time out when reading the file takes longer than the timeout.

Command Log​

List the contents of your package.json file

cy.readFile('package.json')

The command above displays in the Command Log as:

Command Log row showing readFile with the file name package.json

Click the readFile command in the Command Log to see this in the console:

Browser console output for the readFile command, listing the parsed contents of package.json as an object and the full file path

History​

VersionChanges
13.0.0cy.readFile() became a query
9.0.0Changed null encoding to read as Buffer
0.17.2Improved error messaging
0.17.1cy.readFile() command added

See also​