Wednesday, 22 January 2020

Mocking a GET api on button click using Cypress

I'm looking for a way to mock an existing API's response on a button click. When the button, say button A is clicked, the page routes to, let's say #/create-something.

On the FE, there is a loader shown, while in the background there are two XHR requests being made. These two API's response are used to populate two form fields on #/create-something.

The page throws a console error if I don't load these two api's. So, I want to mock these two api's and populate the two form fields using these mocked response.

This is what I'm looking to perform -

  1. Click on button A
  2. Mock the two API's so that form fields X and Y are populated based on response of mocked API.
  3. Perform some form actions.

I have not done or written code for this part since I'm not familiar with how to go about this problem. I have gone through this tutorial but not able to understand if this is the correct way/approach to solve this issue.

Edit 1 : I am adding an example. Let's say I'm hitting this URL - Cats On the initial page load, there are a couple of XHR calls being made. I want to mock the me and the cats API call using fixtures.

I have a urls file which contains the routes -

urls.js

 export const me='/users/me';
 export const cats='3/gallery/r/cats'

In my cats.spec.js folder, I have this code

   import {
       me,
       cats  
    } from '../cats'

 context('Checking if mocking can be done',()=>{
   const mockingAPI = () =>{
       cy.server();
       cy.route(me, 'fixtures:me-mock.json);
       cy.route(cats,'fixtures:me-cats.json);
       cy.wait(2000);
        }

   describe('Actual mock and tests',()=>{
       before(mockingAPI());

       it('lets add some tests',()=>{
        cy.visit('/');

         })

  })
})

PS - If this has already been asked, please point me to the same.



from Mocking a GET api on button click using Cypress

No comments:

Post a Comment