Currently, I am running tests on express middlewares using jest.
it("should throw 400 error if request.body.id is null", () => {
const req = { body: { id: null } } as any;
const res = {} as any;
const next = jest.fn();
myMiddleware(req, res, next);
expect(next).toBeCalledWith(expect.any(ErrorResponse));
expect(next).toBeCalledWith(
expect.objectContaining({
statusCode: 400,
errCode: "error-0123-2342",
message: "Field id is missing",
})
);
});
The ErrorResponse Class:
export class ErrorResponse extends Error {
public statusCode: number;
public errCode: string;
constructor(
statusCode: number = 500,
errCode: string = "error-123-1993",
message: string = "Internal Server Error"
) {
super(message);
this.statusCode = statusCode;
this.errCode = errCode;
}
}
I have successfully tested for specific properties in the ErrorResponse
Object when called in the next
function. However, I want to ensure that the ErrorResponse Object consists of only three properties (statusCode
, errCode
, message
) even if another property like details
is added to the ErrorResponse
.
I aim to achieve the following and confirm that the ErrorResponse Object comprises just the 3 properties (statusCode
, errCode
, message
).
it("should throw 400 error if request.body.id is null", () => {
const req = { body: { id: null } } as any;
const res = {} as any;
const next = jest.fn();
myMiddleware(req, res, next);
expect(next).toBeCalledWith(
new ErrorResponse(
400,
"error-3123-2332",
"Field id is missing"
)
);
});
Is there a way to accomplish this in jest?