我正在尝试读取我刚刚在同一cypress项目中用另一项测试编写的JSON文件。但是,当它尝试读取文件时,它将在4000毫秒后超时。
有人曾经历过吗?我该怎么解决?
我试图通过给它一个设置对象来增加超时时间,但这并没有增加超时时间。我以为这可能是文件权限问题,但这似乎也不是。
我在Mac上运行,但在Windows上尝试了相同的项目,但结果相同。
before('grab generated user data', function (){
let data = cy.readFile("Generated User/Cypress test 131.json", {log:true, timeout: 180000});
}
我希望它只返回已解析的JSON对象。如赛普拉斯文档中所述。 (https://docs.cypress.io/api/commands/readfile.html#Syntax)
答案 0 :(得分:2)
1。您的文件应位于存在“ cypress.json”文件的项目目录中。
2。您的文件名应为'Cypresstest131.json'或'Cypress-test-131.json'
before('grab generated user data', function (){
let data = cy.readFile("Cypresstest131.json", {log:true, timeout: 4000});
data.its('name').should('eq', 'Eliza')
})
或
before('grab generated user data', function (){
cy.readFile("Cypress-test-131.json", {log:true, timeout: 4000}).its('name').should('eq', 'Eliza')
})
希望对您有帮助
答案 1 :(得分:1)
我最终用cy.createFileSync()创建了一个data.json。当我不想使用cypresses cy.readFile()函数读取文件时,我创建了一个使用fs库读取文件的cypress任务。
我要给你的是我用来读取文件的任务的代码片段。
const fs = require('fs');
const request = require('request');
module.exports = (on, config) => {
on('task', {
// Cypress task to get the last ID
getLastId: () => {
// Make a promise to tell Cypress to wait for this task to complete
return new Promise((resolve) => {
fs.readFile("data.json", 'utf8', (err, data) => {
if (data !== null && data !== undefined) {
data = JSON.parse(data);
if (data.hasOwnProperty('last_id')) {
resolve(data.last_id);
} else {
resolve("Missing last_id");
}
} else {
resolve(err);
}
});
});
}
调用此函数就像
一样简单 let id = 0;
before('grab generated user data', function (){
cy.task('getLastId').then((newID)=>{
id = newID;
});
});