前端自动化测试框架Cypress(十九)-- 读写文件writeFile()、readFile()

25 篇文章 18 订阅
25 篇文章 18 订阅

.writeFile()
语法:

cy.writeFile(filePath, contents)
cy.writeFile(filePath, contents, encoding)
cy.writeFile(filePath, contents, options)

编码方式:

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

写入内容到txt文件

cy.writeFile('path/to/message.txt', 'Hello World')
cy.readFile('path/to/message.txt').then((text) => {
  expect(text).to.equal('Hello World') // true
})

写入json文件

cy.writeFile('path/to/data.json', { name: 'Eliza', email: 'eliza@example.com' })
cy.readFile('path/to/data.json').then((user) => {
  expect(user.name).to.equal('Eliza') // true
})

将在{projectRoot}/path/to/data.json文件中创建以下内容

{
  "name": "Eliza",
  "email": "eliza@example.com"
}

响应数据写入一个夹具文件

cy.request('https://jsonplaceholder.typicode.com/users').then((response) => {
  cy.writeFile('cypress/fixtures/users.json', response.body)
})

// our fixture file is now generated and can be used
cy.fixture('users').then((users) => {
  expect(users[0].name).to.exist
})

指定的编码为字符串

cy.writeFile('path/to/ascii.txt', 'Hello World', 'ascii'))

将在{projectRoot}/path/to/message.txt文件中创建以下内容

Hello World

追加内容到文件

cy.writeFile('path/to/ascii.txt', 'Hello World', { encoding: 'ascii', flag: 'a+' })

.redFile() 读文件
语法:

cy.readFile(filePath)
cy.readFile(filePath, encoding)
cy.readFile(filePath, options)
cy.readFile(filePath, encoding, options)

使用:

cy.readFile('menu.json')

读取.txt文件

// path/to/message.txt

Hello World
cy.readFile('path/to/message.txt').should('eq', 'Hello World') // true

读取json

// data.json

{
  "name": "Eliza",
  "email": "eliza@example.com"
}
cy.readFile('path/to/data.json').its('name').should('eq', 'Eliza') // true

读取YAML

const YAML = require('yamljs')

cy
  .readFile('languages/en.yml')
  .then((str) => {
    // parse the string into object literal
    const english = YAML.parse(str)

    cy
      .get('#sidebar')
      .find('.sidebar-title')
      .each(($el, i) => {
        englishTitle = english.sidebar[i]

        expect($el.text()).to.eq(englishTitle)
      })
  })

编码

cy.readFile('path/to/logo.png', 'base64').then((logo) => {
  // logo will be encoded as base64
  // and should look something like this:
  // aIJKnwxydrB10NVWqhlmmC+ZiWs7otHotSAAAOw==...
})

播放mp3
cy.readFile(‘audio/sound.mp3’, ‘base64’).then((mp3) => {
const uri = ‘data:audio/mp3;base64,’ + mp3
const audio = new Audio(uri)

audio.play()
})

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值