title: How to write a unit test an Express controller using Jest?
body: <p>Thank you for taking the time to read my question. </p>
  
  <p>I am pretty new to Jest and unit testing for that matter, so before I begin writing unit tests for my controller functions, I wanted to check my understanding. So high level, I understand that the unit test is to test whether the controller function behaves as expected when called.</p>
  
  <p>How would I go about writing a Jest unit test for the following code? I would really appreciate an example so that I can reference it as I write the jest tests for the other controllers. Thank you.</p>
  
  <pre><code>//retrieveMember.js
  
  
  const debug = require('debug')('get_member');
  const MemberService = require('../services/MemberService');
  const generateError = require('../lib/generateError');
  
  
  const retrieveMember = async (req, res, next) =&gt; {
    try {
      if (req.params.id === ""
      || req.params.id === undefined) {
        throw generateError(400, "invalid.");
      }
  
      const regex = RegExp("[^a-zA-Z0-9\-]");
      if (regex.test(req.params.id)) {
        throw generateError(400, "invalid format.");
      }
  
      const memberId = req.params.id;
      const memberRecord = await MemberService.retrieveOneMember(memberId);
  
      const member_detail = {
        id: memberRecord.id,
        username: memberRecord.username,
      };
  
      res.status(200).send({member_detail: member_detail});
    } catch (e) {
      if (e) {
        debug('could not get member');
        return next(e);
      }
    }
  };
  
  
  module.exports = retrieveMember;
  </code></pre>