3.4 KiB
title, comments, description
| title | comments | description |
|---|---|---|
| readfile | true |
Reads a file and returns its contents. JSON is automatically parsed into JavaScript.
| Returns | the contents of the file |
| Timeout | cy.readFile will retry for the duration of the defaultCommandTimeout |
cy.readFile( filePath )
Reads the file at the filePath. The filePath is relative to the project's root.
cy.readFile( filePath, encoding )
Reads the file at the filePath with the encoding. The filePath is relative to the project's root.
Options
Pass in an options object to change the default behavior of cy.readFile.
cy.readFile( filePath, options )
cy.readFile( filePath, encoding, options )
| Option | Default | Notes |
|---|---|---|
timeout |
defaultCommandTimeout |
Total time to wait for the cy.readFile command to be processed |
Usage
Read a txt file
For any file other than JSON, the contents of the file are returned.
// message.txt contains:
// Hello World
cy.readFile("path/to/message.txt").then(function (text) {
expect(text).to.equal("Hello World") // true
})
Read a json file
For JSON, the contents are parsed into JavaScript and returned.
// data.json contains:
// {
// "name": "Eliza",
// "email": "eliza@example.com"
// }
cy.readFile("path/to/data.json").then(function (user) {
// user will equal:
// {
// name: "Eliza",
// email: "eliza@example.com"
// }
expect(user.name).to.equal("Eliza")
})
Specify encoding
Specify the encoding with the second argument.
cy.readFile("path/to/logo.png", "base64").then(function (logo) {
// logo will be encoded as base64
// and should look something like this:
// aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
})
The following encodings are supported:
asciibase64binaryhexlatin1utf8utf-8ucs2ucs-2utf16leutf-16le
Notes
Implicit assertion
By default, cy.readFile asserts that the file exists and will fail if it does not exist. It will retry reading the file if it does not initially exist until the file exists or the command times out.
// will fail after the defaultCommandTimeout is reached
cy.readFile('does-not-exist.yaml')
Asserting non-existence
You can assert that a file does not exist like so:
// will pass if the file does not exist
cy.readFile('does-not-exist.yaml').should("not.exist")
Command Log
List the contents of cypress.json
cy.readFile("cypress.json")
The command above will display in the command log as:
When clicking on the readFile command within the command log, the console outputs the following: