我已经更新了cron作业计划程序功能。现在,我需要为此功能更新单元测试用例。对于scheduleJob
的通过日期,其功能为参数。在测试用例中,我需要检查函数toHaveBeenCalled
是否有效。
/**
* @file Scheduler Service.
*/
// Import External Modules
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();
};
}
答案 0 :(得分:1)
您可以使用jest.mock(moduleName, factory, options)模拟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