Вы можете использовать jest.mock (moduleName, factory, options) mock конструктора CronJob
и его экземпляра для модуля cron
.
Например,
index.ts
:
import { CronCommand, CronJob } from 'cron';
// ************* Scheduler Configuration ***************
const TIMEZONE = 'Asia/Kolkata';
// *****************************************************
export class Scheduler {
static scheduleJob = (scheduleDate: Date, scheduleFunction: CronCommand) => {
const date = new Date(scheduleDate);
const scheduleJob = new CronJob(
`0 0 0 ${date.getDate()} ${date.getMonth()} 0-6`,
scheduleFunction,
undefined,
true,
TIMEZONE,
);
scheduleJob.start();
};
}
index.test.ts
:
import { Scheduler } from '.';
import { CronJob } from 'cron';
jest.mock('cron', () => {
const mScheduleJob = { start: jest.fn() };
const mCronJob = jest.fn(() => mScheduleJob);
return { CronJob: mCronJob };
});
describe('62078071', () => {
it('should pass', () => {
const mScheduleJob = new CronJob();
const mDate = new Date(1995, 11, 17);
const mScheduleFunction = jest.fn();
Scheduler.scheduleJob(mDate, mScheduleFunction);
expect(CronJob).toBeCalledWith(`0 0 0 17 11 0-6`, mScheduleFunction, undefined, true, 'Asia/Kolkata');
expect(mScheduleJob.start).toBeCalledTimes(1);
});
});
Результат теста:
PASS stackoverflow/62078071/index.test.ts (14.62s)
62078071
✓ should pass (8ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 16.582s