What is the difference between cy.readFile and cy.fixture in Cypress.io ? In what context should we use cy.readFile and cy.fixture ?
cy.readFile('menu.json')
cy.fixture('users/admin.json') // Get data from {fixturesFolder}/users/admin.json
There are two major differences.
cy.readFile()
starts at your cypress project folder, the folder where your cypress.json
is. In other words, cy.readFile("test.txt")
will read from (path-to-project)\test.txt
.
cy.fixture()
starts in the fixtures folder. cy.fixture("test.txt")
will read from (path-to-project)\cypress\fixtures\test.txt
. Note that this may be different if you have set a fixtures path in your cypress.json
.
Absolute file paths do not appear to be supported here.
cy.fixture()
tries to guess the file's encoding.cy.fixture()
assumes the encoding for certain file extensions while cy.readFile()
does not, except in at least one special case (see below).
For example, cy.readFile('somefile.png')
will interpret it as a text document and just blindly read it into a string. This produces garbage output when printed to console. However, cy.fixture('somefile.png')
will instead read in the PNG file and convert it to a base64-encoded string.
This difference isn't in the ability of the two functions, but instead appears to be in default behavior; if you specify the encoding, both functions act identically:
cy.readFile('path/to/test.png', 'base64').then(text => {
console.log(text); // Outputs a base64 string to the console
});
cy.fixture('path/to/test.png', 'base64').then(text => {
console.log(text); // Outputs the same base64 string to the console
});
cy.readFile()
doesn't always read in plain text. cy.readFile()
gives back a Javascript object when reading JSON files:
cy.readFile('test.json').then(obj => {
// prints an object to console
console.log(obj);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With