While writing unit test for a React application, I came across a situation where I need to mock a network request. I was using sinon for mocking and stubbing. I found that sinon has a fake server that can be used to mock network request. In this article, I will show you how to use sinon fake server to mock network request.

Setup

First, we need to install sinon. We can install it using npm or yarn.

npm install sinon --save-dev

Usage

In this example, we will mock a network request to get a list of users. We will use jsonplaceholder to get the list of users. Here is an example of the network request.

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(json => console.log(json));

We will use sinon fake server to mock the network request. Here is the code to setup the fake server.

As name suggest, fake server will respond to the network request with fake data. We can use respondWith method to specify the response. In this example, we will respond with a list of users.

import sinon from 'sinon';

describe('mocking network request', () => {
  let sinonSandBox: sinon.SinonSandbox;
  let server: sinon.SinonFakeServer;

  beforeEach(() => {
    sinonSandBox = sinon.createSandbox();
    server = sinonSandBox.createFakeServer();
    server.autoRespond = true;
    // server.autoRespondAfter = 100; // delay in ms
    server.respondImmediately = true;

    server.respondWith('GET', 'https://jsonplaceholder.typicode.com/users', [
      200,
      { 'Content-Type': 'application/json' },
      JSON.stringify([
        {
          id: 1,
          name: 'Leanne Graham',
          username: 'Bret',
          email: '[email protected]',
        }
      ])
    ]);

  });    

  afterEach(() => {
    sinonSandBox.restore();
  });

  it('should render a list of users', () => {
    // this test will need mock request to get the list of users
     render(<UserTable/>)
     // expect the list of users to be rendered which is mocked by sinon fake server
  });
  
});

  

In the above code, we create a sinon sandbox and a fake server. We also set the autoRespond and respondImmediately to true. This will make the fake server respond to the request immediately. We also set the response for the request. The response is an array of users. We can also set the response status and headers.

Multiple requests can be mocked using sinon fake server. We can also use sinon fake server to mock other network request such as POST, PUT, DELETE, etc. You need to add the request method as the first parameter of the respondWith method.

Using regex to match URL

We can also use regex to match the URL. Here is an example of using regex to match the URL.

// match any URL that contains jsonplaceholder
server.respondWith('GET', /jsonplaceholder/, [
  200,
  { 'Content-Type': 'application/json' },
  JSON.stringify([
    {
      id: 1,
      name: 'Leanne Graham',
      username: 'Bret',
      email: '[email protected]'
    },
  ]),
]);

Javascript implementation

In the above example, we use typescript. If you are using javascript, you can use the following code to setup the fake server. It would not be much different from the typescript code.

import sinon from 'sinon';

describe('mocking network request', () => {
  let sinonSandBox
  let server

  beforeEach(() => {
    sinonSandBox = sinon.createSandbox();
    server = sinonSandBox.createFakeServer();
    server.autoRespond = true;
    // server.autoRespondAfter = 100; // delay in ms
    server.respondImmediately = true;

    server.respondWith('GET', 'https://jsonplaceholder.typicode.com/users', [
      200,
      { 'Content-Type': 'application/json' },
      JSON.stringify([
        {
          id: 1,
          name: 'Leanne Graham',
          username: 'Bret',
          email: '[email protected]',
        }
      ])
    ]);

  });    

  afterEach(() => {
    sinonSandBox.restore();
  });

  it('should render a list of users', () => {
    // this test will need mock request to get the list of users
     render(<UserTable/>)
     // expect the list of users to be rendered which is mocked by sinon fake server
  });
  
});