最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the difference between cy.readFile and cy.fixture in Cypress.io? - Stack Overflow

programmeradmin4浏览0评论

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

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
Share Improve this question asked Aug 15, 2018 at 23:35 soccerwaysoccerway 11.9k23 gold badges80 silver badges159 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

There are two major differences.


First, the two functions handle filepaths differently.

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.


Second, 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
});

Note:

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);
});
发布评论

评论列表(0)

  1. 暂无评论