Cypress Fixture

Profile picture for user devraj

Cypress Fixture Command is used to load a fixed set of data located in different files including JSON and Image file. cy.fixture() yields the contents of the file where formatting is determined by its file extension. This command does not log in the Command Log.

Table of Content

  1. Syntax
  2. Encoding Formats
  3. Rules
  4. Example
  5. Video

1. Syntax

cy.fixture(filePath)
cy.fixture(filePath, encoding)
cy.fixture(filePath, options)
cy.fixture(filePath, encoding, options)
  • filePath: A path to a file within the fixtures folder defaults to cypress/fixtures. You can create your folder in fixtures and give a path starting from the created folder name.
  • encoding: Mention The encoding to be used when reading the file. Check Encoding Table
  • options: Only accepted options is timeout.

2. Encoding Formats

asciibase64binaryhexlatin1utf8
utf-8ucs2usc-2utf16leutf16-lenull

Cypress automatically determines the encoding for the below file types:

.coffee.csv.gif.html.jpg.jpeg.js
.json.png.tif.tiff.txt.zip 

For other types of files, they will be read as utf8 by default, unless specified in the second argument of cy.fixture(). You can specify null as the encoding in order to read the file as a Cypress.Buffer instance instead.

3. Rules

  1. cy.fixture() requires being chained off of cy .
  2. cy.fixture() will only run assertions you have chained once, and will not retry .
  3. cy.fixture() should never time out.

4. Example

Demo Link: https://www.programsbuzz.com/user/login

cypress fixtures example

We will fill in the username and password value from the user.json file created in the cypress/fixtures folder. Here is the content of the JSON file.

{
  "username": "randomuser",
  "password": "random"
}

Code:

 it.only('fixture demo', () => {
    cy.visit('https://www.programsbuzz.com/user/login')

    cy.fixture('user').then((userdata) => {
        cy.get('#edit-name').type(userdata.username)
        cy.get('#edit-pass').type(userdata.password)
    })
})
  • user is the filename with .json extension optional.  When no extension is passed in the fixture command, Cypress will search for files with the specified name within the fixtures folder and resolve the first one.
  • Using the userdata variable, we are reading username and password key values from the JSON file.
  • Cypress loads the fixture file once. If you want to dynamically change the content of a file, use the readFile command.