Below is a demonstration function I have:
export async function myHandler(
param1: string,
param2: string,
req: Request,
next: NextFunction,
) {
const log = req.log.prefix(`[my=prefix]`);
let res;
If (param1 === 'param1') {
log("GOT PARAM 1");
} else {
res = await doSomething();
}
log("GOT HERE");
..
..
..
..
res.setReturnStatus(200)
}
next();
}
As for the logger, this is the structure of the request containing it:
const req: {
url: string;
params: {};
body: {
device: {
type: string;
p1: string;
p2: string;
p3: string;
};
data: {
sample: number;
};
};
metric: () => jest.Mock<any, any>;
log: {
(): jest.Mock<any, any>;
warn(): jest.Mock<...>;
error(): jest.Mock<...>;
prefix(): jest.Mock<...>;
};
timing: () => jest.Mock<...>;
}
When writing my unit test, I am checking the return status with this line:
expect(res.status).toBeCalledWith(200);
I aim to cover the first 'if' statement, which logs 'GOT PARAM 1', but struggling to intercept the call in the middle.
doSomething = jest.fn(() => Promise.resolve());
await myHandler('param1', 'param1', next); //HERE to somehow verify that was also logged?
expect(res.status).toBeCalledWith(200);
I attempted something like :
const spy = jest.spyOn(req.log, 'log');
resulting in an error:
Cannot spy the log property because it is not a function; undefined given instead