Cypress.io中的cy.readFile和cy.fixture有什么区别?
What is the difference between cy.readFile and cy.fixture in Cypress.io?
cy.readFile 和 Cypress.io 中的 cy.fixture 有什么区别?我们应该在什么情况下使用 cy.readFile 和 cy.fixture ?
cy.readFile('menu.json')
cy.fixture('users/admin.json') // Get data from {fixturesFolder}/users/admin.json
有两个主要区别。
首先,这两个函数处理文件路径的方式不同。
cy.readFile()
从您的 cypress 项目文件夹开始,您的 cypress.json
所在的文件夹。换句话说,cy.readFile("test.txt")
将从 (path-to-project)\test.txt
.
读取
cy.fixture()
从 fixtures 文件夹开始。 cy.fixture("test.txt")
将从 (path-to-project)\cypress\fixtures\test.txt
读取。请注意,如果您在 cypress.json
.
中设置了灯具路径,这可能会有所不同
此处似乎不支持绝对文件路径。
其次,cy.fixture()
尝试猜测文件的编码。
cy.fixture()
假设某些文件扩展名的编码而 cy.readFile()
不假设,除了至少一种特殊情况(见下文).
比如cy.readFile('somefile.png')
会把它解释成一个文本文档,只是盲目地读成一个字符串。当打印到控制台时,这会产生垃圾输出。但是,cy.fixture('somefile.png')
将读取 PNG 文件并将其转换为 base64 编码的字符串。
这种区别不在于这两个函数的能力,而在于默认行为;如果您指定编码,两个函数的行为相同:
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()
并不总是以纯文本形式阅读。 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);
});
cy.readFile 和 Cypress.io 中的 cy.fixture 有什么区别?我们应该在什么情况下使用 cy.readFile 和 cy.fixture ?
cy.readFile('menu.json')
cy.fixture('users/admin.json') // Get data from {fixturesFolder}/users/admin.json
有两个主要区别。
首先,这两个函数处理文件路径的方式不同。
cy.readFile()
从您的 cypress 项目文件夹开始,您的 cypress.json
所在的文件夹。换句话说,cy.readFile("test.txt")
将从 (path-to-project)\test.txt
.
cy.fixture()
从 fixtures 文件夹开始。 cy.fixture("test.txt")
将从 (path-to-project)\cypress\fixtures\test.txt
读取。请注意,如果您在 cypress.json
.
此处似乎不支持绝对文件路径。
其次,cy.fixture()
尝试猜测文件的编码。
cy.fixture()
假设某些文件扩展名的编码而 cy.readFile()
不假设,除了至少一种特殊情况(见下文).
比如cy.readFile('somefile.png')
会把它解释成一个文本文档,只是盲目地读成一个字符串。当打印到控制台时,这会产生垃圾输出。但是,cy.fixture('somefile.png')
将读取 PNG 文件并将其转换为 base64 编码的字符串。
这种区别不在于这两个函数的能力,而在于默认行为;如果您指定编码,两个函数的行为相同:
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()
并不总是以纯文本形式阅读。 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);
});