automated-testscypresscypress-intercept

Cypress - Page Load Fails despite loading correct JSON


I'm trying to learn Cypress. And I'm trying to intercept an API call and return a fixed JSOn response. It works correctly with all responses being sent, and the page loads in the IDE too but Cypress returns an error with "Failed to load" Here's the code:

it.only('mocking api with intercept using static response', function(){

    cy.intercept({
        method: 'GET', // route all GET calls 
        url: '/typicode/demo' // that go to this URL
    },
    { body: ['forcing response to be this'] } // and force response to be this
    ).as('demo')

    cy.visit('https://my-json-server.typicode.com/', {
        failOnStatusCode: false
    })
    cy.get('.hero > .container > .action > .button').click()

    cy.wait('@demo').its('response.statusCode').should('eq', 200);


})

Here's what the IDE looks like: enter image description here

And here is what the Network tab looks like: enter image description here

I just don't know what I'm doing wrong. This is a mock/dummy website, so y'all can try to replicate this if you want. Help please! :(


Solution

  • The non-mocked response is HTML, which you can see if you run this code

    cy.intercept('/typicode/demo').as('demo')
    
    cy.contains('try a server').click()
    
    cy.wait('@demo')
      .its('response.body')
      .then(body => console.log(body))
    

    yields

    <!DOCTYPE html>
      <html>
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width" initial-scale="1" />
           <title>My JSON Server - Fake online REST server for teams</title>
             ...
    

    so your mocked response should adhere to the expected type, something like

    cy.visit('https://my-json-server.typicode.com/')
    
    cy.intercept('/typicode/demo', { body: '<div>forcing response to be this</div>' })
      .as('demo')
    
    cy.contains('try a server').click()
    
    cy.wait('@demo')
    
    cy.get('div').should('have.text', 'forcing response to be this')
    

    enter image description here