Dynamically Combine Real and Mocked Response Body Data in Cypress

Filip Hric
InstructorFilip Hric

Share this video with your friends

Send Tweet
Published 3 months ago
Updated 3 months ago

When a static response is not enough, we can take the real data from server and modify it to our liking. This saves a ton of time, because we don’t need to create the data ourselves. Instead, we can take e.g. response body and change only a desired attribute. This gives us one more advantage, because we can first make assertions on real data, and only then make changes. This is a great advantage compared to providing a static response, that essentially creates a blind spot for any API changes.

Instructor: [0:00] With dynamic intercepting, I can change, basically, any part of the request or the response. To change my response dynamically, I have a reply function, which will take a response as a parameter in my callback function. For starters, I can just console log it out.

[0:26] When I now save my test, I can see all of my boards. I can see that the whole response is printed out inside the console. If I want to change the body and change, for example, the first board's name, I can go ahead and type, This Body, index number of zero, name, and change the value to, "Philips Birthday Party," close my console, so you can see, and save the test.

[0:58] You'll see that the value inside is changed now. The cool thing about this is that I'm combining real and fake data. When I click on this board, I can see that it has content. Although, the name is not changed in this view because there's a separate endpoint that is loading this. When I go back to my view, I can again see the changed name of the board.

[1:23] One thing with stabbing our data is that we cannot really be sure if the API is still returning the data in the same structure. To change that, we can first write the test for the attribute, Expect This Body Name to Exist. Only then, change it.

[1:47] If this assertion fails, we will actually find out. If it doesn't, then we dynamically change our data. When I now save my test, I first check that the original value exists and then I'll dynamically change it.