Home > Enterprise >  How can I test node cron on Jest
How can I test node cron on Jest

Time:12-14

I'm testing my API with supertest package, I do have a business logic that when a property qrCodeDate is less than Date.now() the User status becomes inactive.

import { CronJob } from 'cron';

export default (Model) =>
    new CronJob(
        '0 1 * * *',
        async function () {
            await Model.updateMany(
                { qrCodeDate: { $lt: new Date(Date.now()) } },
                { $set: { status: 'INACTIVE', qrCodeDate: null } }
            );
        },
        null
    );

On userModel.ts:

// Cron Job to verify if Date.now() > qrCodeDate
const job = CronJob(UserModel);
job.start();

And in users.test.ts I doing something like this: expect(User['status']).toBe('INACTIVE');

On my app, I got those CronJob running everyday checking the condition previously mentioned, anyway, in my test I don't know how to implement, also need the commented line for TS types

import { CronJob } from 'cron';
jest.mock('cron');

xtest('Check if when QR Code expires, ordinary status back to INACTIVE', async () => {
        
        // (CronJob as unknown as jest.Mock)

        expect(User['status']).toBe('INACTIVE');
    });

Thanks in advance.

CodePudding user response:

You do not need to test the cron module in your project. You just need to test the logic inside the function where you are calling Model.updateMany. You can just declare that function separately not in the argument, give it a name and write tests for that function

  • Related