作用

使读取文件并返回内容

语法格式

  1. cy.readFile(filePath)
  2. cy.readFile(filePath, encoding)
  3. cy.readFile(filePath, options)
  4. cy.readFile(filePath, encoding, options)

filePath

项目根目录(包含默认 cypress.json 配置文件的目录)中需要读取的文件的路径

encoding

读取时需要使用的编码

  • ascii
  • base64
  • binary
  • hex
  • latin1
  • utf8
  • utf-8
  • ucs2
  • ucs-2
  • utf16le
  • utf-16le

options

  • log:是否将命令显示到命令日志中,默认 true
  • timeout:命令超时时间

正确用法

  1. cy.readFile('users.json')

命令返回结果

文件内容

读取 txt 文件的栗子

测试代码

Cypress系列(94)- readFile() 命令详解 - 图1

运行结果

Cypress系列(94)- readFile() 命令详解 - 图2

读取 json 文件的栗子

json 文件数据

  1. {
  2. "id": 1,
  3. "name": "Leanne Graham",
  4. "username": "Bret",
  5. "email": "Sincere@april.biz",
  6. "address": {
  7. "street": "Kulas Light",
  8. "suite": "Apt. 556",
  9. "city": "Gwenborough",
  10. "zipcode": "92998-3874",
  11. "geo": {
  12. "lat": "-37.3159",
  13. "lng": "81.1496"
  14. }
  15. }
  16. }

测试代码

Cypress系列(94)- readFile() 命令详解 - 图3

运行结果

Cypress系列(94)- readFile() 命令详解 - 图4
读取出来是一个属性对象

读取 yaml 文件的栗子

yaml 文件

  1. - 1
  2. - 2
  3. - 3


测试代码

Cypress系列(94)- readFile() 命令详解 - 图5

运行结果

Cypress系列(94)- readFile() 命令详解 - 图6

yaml 扩展使用

  1. YAML = require('yamljs');
  2. // 解析 YAML 文件
  3. nativeObject = YAML.parse(yamlString);
  4. // 生成 YAML 字符串
  5. yamlString = YAML.stringify(nativeObject, 4);
  6. // 加载 YAML 文件
  7. nativeObject = YAML.load('myfile.yml');

读取图片的栗子

测试代码

Cypress系列(94)- readFile() 命令详解 - 图7

运行结果

Cypress系列(94)- readFile() 命令详解 - 图8

读取 mp3 文件的栗子

测试代码

Cypress系列(94)- readFile() 命令详解 - 图9

运行结果

Cypress系列(94)- readFile() 命令详解 - 图10

读取 mp4 文件的栗子

测试代码

Cypress系列(94)- readFile() 命令详解 - 图11

运行结果

Cypress系列(94)- readFile() 命令详解 - 图12

https://www.cnblogs.com/poloyy/p/14039551.html