writeFile
向指定文件写入内容。
语法
cy.writeFile(filePath, contents)
cy.writeFile(filePath, contents, encoding)
cy.writeFile(filePath, contents, options)
cy.writeFile(filePath, contents, encoding, options)
用法
正确用法
cy.writeFile('menu.json')
参数
filePath (String)
项目根目录(包含Cypress配置文件的目录)中的文件路径。
contents (String, Array, Object 或 Buffer)
要写入文件的内容。
encoding (String)
写入文件时使用的编码。支持以下编码:
'ascii'
'base64'
'binary'
'hex'
'latin1'
'utf8'
'utf-8'
'ucs2'
'ucs-2'
'utf16le'
'utf-16le'
null
显式使用null
可以直接写入Buffer
,而无需先将其编码为字符串。
options (Object)
传入一个选项对象以更改cy.writeFile()
的默认行为。
选项 | 默认值 | 描述 |
---|---|---|
log | true | 在命令日志中显示该命令 |
flag | w | 文件系统标志,与fs.writeFile 相同 |
encoding | utf8 | 写入文件时使用的编码 |
timeout | defaultCommandTimeout | 等待.writeFile() 解析的时长,超过则超时 |
info
要将编码与其他选项一起使用,请将选项对象作为第三个参数,并在其中包含编码。这与fs.writeFile
的行为相同。
生成结果
cy.writeFile()
返回null
。
示例
文本
向txt
文件写入文本
如果文件路径不存在,将创建该文件及其路径。如果文件已存在,将被覆盖。
cy.writeFile('path/to/message.txt', 'Hello World')
cy.readFile('path/to/message.txt').then((text) => {
expect(text).to.equal('Hello World') // true
})
{projectRoot}/path/to/message.txt
将创建并包含以下内容:
"Hello World"
JSON
向文件写入JSON
JavaScript数组和对象将被字符串化并格式化为文本。
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"
}
将响应数据写入fixture文件
cy.request('https://jsonplaceholder.typicode.com/users').then((response) => {
cy.writeFile('cypress/fixtures/users.json', response.body)
})
// 现在可以生成并使用我们的fixture文件
cy.fixture('users').then((users) => {
expect(users[0].name).to.exist
})