#Cron unit test with deleteCronJob()

1 messages · Page 1 of 1 (latest)

cinder tree
#

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

plucky vigil
#

didnt read he SO posts, but you don't test the actual cron. That is already tested for you. You test the handler, nothing more, nothing less.

cinder tree
cinder tree
#

Cron unit test with deleteCronJob()