0

My goal is to land on a page

Ex: www.example.com

When I land on this page a particular API is hit, I want to intercept that API and store the json response in a variable and extract specific values from the response.

I have tried this code but it fails after waiting for 5 seconds:

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);
          });
      });
  });
});
Blunt
  • 154
  • 7
suresh
  • 1
  • 2
  • In the Cypress runner, are you seeing the intercept being hit at all? Your intercept may be getting hit before you tell Cypress to wait for it. – agoff Feb 02 '23 at 16:22

1 Answers1

4

If you change the test slightly, it works without a hitch!

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);
          })
      })
  })
})

logs this to console

<!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>

Given that your example works, what else can you tell us about the test that might allow us to see the issue?

  • If you need clarification from the poster, you should post a comment – DJSDev Feb 03 '23 at 04:48
  • 1
    The answer is useful, it points out the pattern for intercepting is correct. – Blunt Feb 03 '23 at 10:16
  • The answer is useful, but I brought this up because they were asking for clarification at the end of their answer. If they need more clarification from the poster, they should post a comment. – DJSDev Feb 05 '23 at 06:11