我想编写cypress脚本来拦截API响应并将json响应存储在变量中,并从响应中提取特定值

问题描述 投票:0回答:1

我的目标是登陆页面

例如:www.example.com

当我登陆此页面时,会点击特定的 API,我想拦截该 API 并将 json 响应存储在变量中,并从响应中提取特定值。

我已经尝试过这段代码,但等待 5 秒后失败:

describe('Intercept API response', () => {
  it('Stores the response in a variable', () => {
    let responseData;

    cy.intercept('GET', 'https://jsonplaceholder.typicode.com/posts/1').as('getData');

    cy.visit('https://www.example.com')
      .then(() => {
        cy.wait('@getData')
          .then((xhr) => {
            responseData = xhr.response.body;
            console.log(responseData);
          });
      });
  });
});
cypress webapi cypress-intercept
1个回答
5
投票

如果你稍微改变一下测试,它就可以顺利运行!

describe('Intercept API response', () => {
  it('Stores the response in a variable', () => {
    let responseData;

    // lets try to intercept the actual domain

    cy.intercept('GET', 'http://www.example.com').as('getData');

    cy.visit('http://www.example.com')
      .then(() => {
        cy.wait('@getData')
          .then((xhr) => {
            responseData = xhr.response.body;
            console.log(responseData);
          })
      })
  })
})

将其记录到控制台

<!doctype html>
<html>
<head>
    <title>Example Domain</title>

</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

鉴于您的示例有效,您还能告诉我们有关该测试的哪些信息,以便我们可以发现问题?

© www.soinside.com 2019 - 2024. All rights reserved.