如何在 Jest 上测试节点 cron

How can I test node cron on Jest

我正在用 supertest 包测试我的 API,我确实有一个业务逻辑,当 属性 qrCodeDate 小于 Date.now() User 状态变为无效。

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
    );

在 userModel.ts:

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

然后在 users.test.ts 中我做了这样的事情:expect(User['status']).toBe('INACTIVE');

在我的应用程序上,我得到了那些 CronJob 运行 每天检查前面提到的条件,无论如何,在我的测试中我不知道如何实现,还需要 TS 类型的注释行

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');
    });

提前致谢。

您不需要在项目中测试 cron 模块。 您只需要测试调用 Model.updateMany 的函数内部的逻辑。 您可以单独声明该函数而不是在参数中,为其命名并为该函数编写测试