I developed a unique Express middleware that validates if the request content type is JSON. If it's not, the server will return a 415 error along with a custom error object.
import { Request, Response, NextFunction } from "express";
function enforceContentTypeApplicationJson() {
return (request: Request, response: Response, next: NextFunction) => {
if (!request.is("application/json")) {
response.setHeader('Content-Type', 'application/json');
response.statusCode = 415;
const actualContentType = request.get("Content-Type") ?? "";
const errorResult = {
isSuccessful: false,
error: `Expected Content-Type 'application/json' but got '${actualContentType}'.`,
};
response.json(errorResult);
return;
}
next();
};
}
To validate this middleware using Jest, I've written my initial test as follows:
it("checks for status code 415 when header 'Content-Type' is not 'application/json'.", () => {
const contentType = "multipart/form-data";
const mockRequest: Partial<Request> = {
headers: {
"Content-Type": contentType,
},
is: jest.fn().mockImplementation(() => false),
get: jest.fn().mockImplementation(() => contentType),
};
const mockResponse: Partial<Response> = {
json: jest.fn(),
setHeader: jest.fn().mockImplementation(function (name, value) {
(this as unknown as Response).setHeader(name, value);
}),
};
const nextFunction: NextFunction = jest.fn();
const expectedResponse = {
isSuccessful: false,
error: `Expected Content-Type 'application/json' but got '${contentType}'.`,
};
const middleware = enforceContentTypeApplicationJson();
middleware(mockRequest as Request, mockResponse as Response, nextFunction);
expect(mockResponse.statusCode).toBe(415);
// expect(mockResponse.getHeader('Content-Type')).toBe('application/json');
// expect(mockResponse.getHeaders?.()["Content-Type"]).toBe('application/json');
// expect(mockResponse.getHeader?.("Content-Type")).toBe('application/json');
expect(mockResponse.json).toBeCalledWith(expectedResponse);
});
However, I'm facing an issue with mockResponse.setHeader
causing the testrunner to throw an error:
this.setHeader is not a function
How can I effectively mock the setHeader
method for the Response
type? I aim to create a mock implementation to also assert on the response content-type by providing a mock for the getHeader
method in the future.