.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()
})