You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中将API响应体以对象数组形式写入JSON文件?

如何用Cypress将API响应体以对象数组形式写入JSON文件

直接生成单对象数组

如果只需要把当前API返回的单个对象存储为数组格式,只需将响应体包裹进数组后写入文件:

it('Write File Test', function() {
    cy.request('GET', 'http://localhost:3000/users/293')
        .then((resp) => {
            // 将响应对象包裹为数组
            cy.writeFile('cypress/fixtures/writeFile.json', [resp.body]);
        });
});

运行后writeFile.json会生成你需要的格式:

[
    {
     "userid": 293,
     "username": "ramondz",
     "isactive": "active",
     "email": "ramon.dz@test.com"
    }
]

追加到现有数组(避免覆盖)

如果需要后续向同一文件添加更多对象,而非每次覆盖,可先读取现有文件内容(文件不存在则初始化为空数组),再将新对象追加到数组中:

it('Append User to Array', function() {
    cy.request('GET', 'http://localhost:3000/users/293')
        .then((resp) => {
            // 读取现有文件,不存在则返回空数组
            cy.readFile('cypress/fixtures/writeFile.json').catch(() => [])
                .then((existingUsers) => {
                    // 合并现有数组与新用户对象
                    const updatedUsers = [...existingUsers, resp.body];
                    // 写入更新后的数组
                    cy.writeFile('cypress/fixtures/writeFile.json', updatedUsers);
                });
        });
});

问题说明

你之前预先创建空数组仍被覆盖,是因为cy.writeFile默认会完全替换文件内容,直接写入了单个对象。通过主动将对象包裹为数组,或先读取现有数组再追加,就能实现目标格式。

内容的提问来源于stack exchange,提问作者rino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:21:08