I am writing unit test case(jest) for a method which return anonymous function. for the function i need to pass entity name and for anonymous function, it takes this(mongoose response) and next(express) as a arguments. how to mock or pass value to this while calling the validate method?
Method
validatesss(entityName: string) {
return async function (this: any, next: HookNextFunction) {
const sequence = await metadataModel.getIncrementedSequence(entityName);
this.set({ [entityName + '_no']: sequence });
next();
};
}
this
can be provided to a function with call
or apply
:
let next = jest.fn();
let set = jest.fn();
let fn = obj.validatesss('foo');
expect(fn).toEqual(expect.any(Function));
await fn.call({ set }, next);
expect(set).toBeCalledWith({ foo_no: ... });
expect(next).toBeCalledWith();