How to mock express response object in node tests using mocha?

Member

by lizzie , in category: Javascript , 3 months ago

How to mock express response object in node tests using mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 3 months ago

@lizzie 

To mock an Express response object in Node tests using Mocha, you can use a library like sinon to create a stub of the response object. Here's an example of how you can mock an Express response object in a Mocha test:

  1. Install sinon package:
1
npm install --save sinon


  1. In your test file, import sinon and the Express module:
1
2
const sinon = require('sinon');
const express = require('express');


  1. Create a stub of the Express response object before running your test:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
describe('YourTestSuiteName', () => {
  let res;

  beforeEach(() => {
    res = {
      status: sinon.stub().returnsThis(),
      send: sinon.stub()
    };
  });

  it('should test something with mocked response object', () => {
    // Your test code goes here
  });
});


  1. In your test case, you can then use the res object as a mock of the Express response object:
1
2
3
4
5
6
7
it('should test something with mocked response object', () => {
  // Call your Express route handler function with the mock response object
  yourRouteHandler(req, res);

  // Assert the response was sent with the expected data
  sinon.assert.calledWith(res.send, 'Your expected response');
});


By following these steps, you can successfully mock an Express response object in your Mocha tests using sinon.