0

I read some tips on how to mock your request/response in Express framework in the blog: https://codewithhugo.com/express-request-response-mocking/. However, I have no clue how to mock the controller below.

export const healthCheck = async (req, res, next) => {
    log("debug", "healthCheck controller called");
    
    const healthcheck = {
      uptime: process.uptime(),
      message: "Server is running!",
      now_timestamp: Date.now()
    };
    
    try {
      res.send(healthcheck);
    } catch (error) {
      healthcheck.message = error;
      res.status(503).send();
    }
};

I am glad to share my efforts below. My suspicion is that I must mock class Date as well.

import { 
  healthCheck
} from "../healthcheck.js";

const mockRequest = () => {
  const req = {}
  
  req.body = jest.fn().mockReturnValue(req)
  req.params = jest.fn().mockReturnValue(req)
  
  return req
};

const mockResponse = () => {
  const res = {}

  res.get = jest.fn().mockReturnValue(res)
  res.send = jest.fn().mockReturnValue(res)
  res.status = jest.fn().mockReturnValue(res)
  res.json = jest.fn().mockReturnValue(res)
  
  return res
};

const mockNext = () => {
  return jest.fn()
};

describe("healthcheck", () => {
  afterEach(() => {
    // restore the spy created with spyOn
    jest.restoreAllMocks();
  });

  it("should call mocked log for invalid from scaler", async () => {
      
      let req = mockRequest();
      let res = mockResponse();
      let next = mockNext();
      
      await healthCheck(req, res, next);

      expect(res.send).toHaveBeenCalledTimes(1)
      expect(res.send.mock.calls.length).toBe(1); 
      
  });
});

  • Don't test controllers like this. You don't own the Express interface, you shouldn't be mocking it. But if you want to know how to mock dates in Jest, _research it_: https://stackoverflow.com/q/29719631/3001761. – jonrsharpe Dec 02 '22 at 15:28
  • How is is a possible correct way to test controllers? – Bruno Peixoto Dec 02 '22 at 15:36
  • _Integration_ testing, making requests and asserting on responses - test their behaviour not their implementation. – jonrsharpe Dec 02 '22 at 15:44

0 Answers0