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
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
ascii | base64 | binary | hex | latin1 | utf8 |
utf-8 | ucs2 | usc-2 | utf16le | utf16-le | null |
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
- cy.fixture() requires being chained off of cy .
- cy.fixture() will only run assertions you have chained once, and will not retry .
- cy.fixture() should never time out.
4. Example
Demo Link: https://www.programsbuzz.com/user/login
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.
- Log in to post comments