I created a unit test for a NestJS according to: https://stackoverflow.com/questions/71469500/how-to-write-a-unit-test-for-cronjob-in-nestjs
`@Injectable()
export class CronService {
...
async addCronJob(name: string, cronTime: string, cronAction: () => void | Promise<void>): Promise<void> {
const job = new CronJob(cronTime, cronAction)
this.schedulerRegistry.addCronJob(name, job)
job.start()
this.logger.log(
`Cron job '${name}' added with cron time ${cronTime}!`,
)
}
deleteCron(name: string) {
this.schedulerRegistry.deleteCronJob(name);
this.logger.log(Cron job '${name}' deleted!);
}
}`
Testing:
`let cronService: CronService;
let schedulerRegistryMock: SchedulerRegistry
...
describe('addAndDeleteCronJob', () => {
it('Should add and delete cron job', async () => {
jest.useFakeTimers()
const name: string = 'TestCronJob'
const cronTime: string = '0 * * * *'
const cronAction: () => void = jest.fn(() => logger.log('Task executed!'))
await cronService.addCronJob(name, cronTime, cronAction)
expect(cronAction).not.toHaveBeenCalled()
expect(schedulerRegistryMock.addCronJob).toHaveBeenCalledWith(name, expect.any(CronJob))
jest.advanceTimersByTime(60 * 60 * 1000)
expect(cronAction).toHaveBeenCalledTimes(1)
cronService.deleteCron(name)
jest.advanceTimersByTime(60 * 60 * 1000)
expect(cronAction).toHaveBeenCalledTimes(1)
})
})
})`
The test for creating the job works good!
But testing my handler for deletion of the cron job deleteCron() seems not to work, as the second call of expect(cronAction).toHaveBeenCalledTimes(1) after jest.advanceTimersByTime(60 * 60 * 1000) receives 2 calls of cronAction(). How should I test the deletion of the cron job?
See also: https://stackoverflow.com/questions/77081577/nestjs-cron-unit-test-for-deletecronjob
I am facing difficulty writing a unit test in jest for the code snippet below:
async addCronJob(props: IAddAndUpdateCronJobDetails) {
const {name, individualSchedule} = props;
const parsedCro...
I created a unit test for a NestJS according to: How to write a unit test for CronJob in Nestjs
@Injectable()
export class CronService {
private readonly logger = new Logger(CronService.name)