gpt4 book ai didi

cypress - 将响应正文中的对象写入数组中 cypress 中的 JSON 文件

转载 作者:行者123 更新时间:2023-12-02 17:57:53 25 4
gpt4 key购买 nike

我一直在测试如何使用 Cypress 将 API 响应正文写入固定装置中的文件。

it('Write File Test', function() {
cy.request('GET', 'http://localhost:3000/users/293')
.then((resp) => {
cy.writeFile('cypress/fixtures/writeFile.json', resp.body);
});
});

fixture 中的文件最初并未创建。运行此测试时,创建了 json 文件并以此格式存储响应正文:

{
"userid": 293,
"username": "ramondz",
"isactive": "active",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a6b5b9bbbafab0ae94a0b1a7a0fab7bbb9" rel="noreferrer noopener nofollow">[email protected]</a>"
}

我希望这个对象以这种格式存储在 JSON 文件内的数组中:

[
{
"userid": 293,
"username": "ramondz",
"isactive": "active",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a1b2bebcbdfdb7a993a7b6a0a7fdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>"
}
]

实际上,我尝试在fixture中创建一个空主体[]的json文件,然后运行测试。文件中的文本被覆盖,并且我始终将响应正文存储为对象。我无法进入方括号内。

是否可以选择将响应正文存储为对象数组。请有人帮忙吗?

最佳答案

取决于 resp.body 是字符串还是对象。

其中一个应该有效

it('Write File Test', function() {
cy.request('GET', 'http://localhost:3000/users/293')
.then((resp) => {
const respArray = [resp.body];
cy.writeFile('cypress/fixtures/writeFile.json', respArray);
});
});
it('Write File Test', function() {
cy.request('GET', 'http://localhost:3000/users/293')
.then((resp) => {
const respArray = JSON.stringify([resp.body]);
cy.writeFile('cypress/fixtures/writeFile.json', respArray);
});
});
it('Write File Test', function() {
cy.request('GET', 'http://localhost:3000/users/293')
.then((resp) => {
const respArray = '[' + JSON.stringify(resp.body) + ']';
cy.writeFile('cypress/fixtures/writeFile.json', respArray);
});
});

关于cypress - 将响应正文中的对象写入数组中 cypress 中的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75209317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com