Mock But Verify

Verify the web requests while mocking the backend responses.

Network API calls made by your frontend code are a contract. The frontend code A sends a request following a certain protocol (REST / GraphQL / some OpenAPI schema) and expects the server code B to produce the response following the contract schema.

Request made by frontend code A receives response generated by the server code B

The frontend code cannot suddenly change what is sends in the request object without breaking the contract. Yet our end-to-end tests that using network stubbing with cy.intercept often do not notice any such contract changes.

1
2
3
// works the same, even if the frontend suddenly sends
// nonsense "POST /todos body="YAHOOO!!!" instead of { title, completed, id } object
cy.intercept('POST', '/todos', { fixture: 'one-todo.json' })

We can do better. My plugin cypress-magic-backed does not simply replay previously recorded network calls. It also inspects the requests sent by the frontend to ensure they still follow the same "pattern" as before when the network calls were recorded.

Replay mode checks the made request and warns about any unexpected changes

If the frontend code sends something else, the plugin warns us. The video below shows what happens when the Replay mode I use for speedy testing "sees" a change in the object sent by the POST /todos network call.

The test network API recording in this test "knows" about the network call, this is what it has for the first item added:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"method": "POST",
"url": "/todos",
"request": {
"title": "item 1",
"completed": false,
"id": "6950032366"
},
"response": {
"title": "item 1",
"completed": false,
"id": "6950032366"
},
"duration": 1011
}

So when the developer changes the object to have the field "text" instead of field "title", the plugin does not simply return { title, completed, id } back in response to the POST /todos call. It also warns the developer about the observed change. This provides the feedback on any unexpected changes to the network call contract between the frontend and the backend code. This change might be intended, but it might be a simple mistake. By warning the user immediately, we allow the developer to find the very first moment the unexpected change happens.

📺 You can watch the full video explaining and showing the "Mock But Verify" replay mode in this video.