All you need to know about Mocking Strategies and Mock APIs

All you need to know about Mocking Strategies and Mock APIs

Introduction

  • Mocking and stubbing are terms/techniques closely related to testing.
  • Let us look in detail at these two terms.

Mocking Strategies

There are mainly two mocking strategies:

1. Client-side mocking (or simply mocking)

  • Generally, mocking is the action of substituting a piece of software with another, seemingly compatible piece.
  • In other words, mocking means replacing one or more functions with a fake copy.
  • It aims at replacing the outgoing dependencies of our tests.
  • No request is actually made by the client to the server. Instead, the request is made to the client itself.
  • It alters the actual code under test.
  • Eg: fetch(url) { return new Response('hello') }
  • The above piece of code will always return a mocked response whenever fetch is called.
  • Libraries like MirageJS and Axios (interceptor) can help us achieve client-side mocking by providing a fake response.
  • Screenshot_11.png

2. Server-side mocking (Also called stubbing)

  • Generally, stubbing means replacing some external service, or a network response, with a fake version.
  • It aims at replacing incoming dependencies, like a network response.
  • Here, a request is made by the client to the server.
  • It doesn't alter the actual code under test.
  • Eg: fetch(url) { return response.json(); }
  • The above piece of code will always return a response from the server whenever fetch is called.
  • Libraries like JSON-Server can help us achieve server-side mocking.
  • Screenshot_12.png

Mock API

What is a mock API (also called fake API)?

  • A mock API is a mocked-up/fake API.
  • It simulates/imitates the fetching of data from a fake server (from a specific route/endpoint) and returns the response.
  • This process is called API mocking (also called mocking an API response) Eg: JSON-server, JSON-server-graphql, Mockoon
  • Mock APIs are very useful in testing our code.

Why do we use mock APIs, especially during testing?

  • Mock APIs are very convenient to make HTTP calls/requests.
  • Real APIs could be a paid service. They are rate-limited (like only a few requests per day) and are very slow.

What is Mirage.js?

  • Mirage.js is an API Mocking Library which helps us mock an API response.
  • It helps us to create fake backend APIs easily.
  • Mirage.js is a client-side mocking framework. This means that it mocks APIs only in the browser.

How does Mirage.js work?

  • Mirage.js sets up a “fake” server to serve as if in production without actually setting up a real server and thus helps us to create fake backend APIs.
  • When a request is sent by the client, Mirage JS intercepts it and provides a fake response.
  • Eg: We can intercept the call to the endpoint /api/users/ with Mirage.js, and then return a fake response.