【问题标题】:Cypress: Stubbing a particular key in JSON response赛普拉斯:在 JSON 响应中存根特定键
【发布时间】:2020-11-02 08:15:10
【问题描述】:

我想在赛普拉斯中存根以下响应。特别是存根键 ds_version,它的可能值可能是 0、1 或 2。每个值都会在 UI 上显示不同的元素。

fixtures/user.json

{
"email": "test@test.com",
"firstName": "Test",
"lastName": "Test",
"ds_version": 0, --> switch this value to 0, 1, 2 for different test scenarios
"country": "Indonesia",
...
}

我可以通过将整个 JSON 提供为 cy.route() 参数来实现这一点,如下所示:

cy.server();
cy.route('GET', '/users/current', 'fixture:user.json').as('getUsersCurrent');

看来,如果我想测试ds_version=1ds_version=2,我需要提供不同的 JSON 并更改值。有没有办法提供不同的 ds_version 值,而 JSON 的其余部分保持不变?

【问题讨论】:

  • 您可以使用 cypress 的 cy.route2()。要启用它,请写入您的 cypress.json "experimentalNetworkStubbing": true。在您的测试文件cy.route2('GET', '/users/current', 'fixture:user.json', (req) => { req.reply((res) => { let list = JSON.parse(res.body);list.ds_version = 1;res.send(list);})}) 中。试试这个。
  • 谢谢@AlapanDas。相当出色的功能,实际上我不需要使用fixture(所以我不需要事先准备任何JSON)。 ``` cy.route2('GET', '/users/current', (req) => { req.reply((res) => { let responseBody = JSON.parse(res.body); responseBody.ds_version = 2; res.send(responseBody); }) }).as('getUsersCurrent');```
  • 那么它解决了你的问题吗?如果是,我会将其发布为答案,以便对其他人也有帮助。
  • 是的,它确实解决了我的问题!

标签: javascript cypress


【解决方案1】:

您可以使用 cypress 的 cy.route2()

  1. 转到cypress.json 并写"experimentalNetworkStubbing": true

  2. 在您的 test.spec 文件中写入:

    cy.route2('GET', '/users/current', (req) => {
        req.reply((res) => {
            let list = JSON.parse(res.body)
            list.ds_version = 1
            res.send(list)
        })
    })
    

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多