2024-07-16 11:42:48 -07:00
|
|
|
import { mock } from 'jest-mock-extended';
|
2024-09-30 06:38:56 -07:00
|
|
|
import type { Workflow } from 'n8n-workflow';
|
2024-07-16 11:42:48 -07:00
|
|
|
|
2024-08-22 02:46:13 -07:00
|
|
|
import type { InstanceSettings } from '@/InstanceSettings';
|
2024-07-16 11:42:48 -07:00
|
|
|
import { ScheduledTaskManager } from '@/ScheduledTaskManager';
|
|
|
|
|
|
|
|
describe('ScheduledTaskManager', () => {
|
2024-08-22 02:46:13 -07:00
|
|
|
const instanceSettings = mock<InstanceSettings>({ isLeader: true });
|
2024-07-16 11:42:48 -07:00
|
|
|
const workflow = mock<Workflow>({ timezone: 'GMT' });
|
|
|
|
const everyMinute = '0 * * * * *';
|
|
|
|
const onTick = jest.fn();
|
|
|
|
|
|
|
|
let scheduledTaskManager: ScheduledTaskManager;
|
|
|
|
|
|
|
|
beforeEach(() => {
|
|
|
|
jest.clearAllMocks();
|
|
|
|
jest.useFakeTimers();
|
2024-08-22 02:46:13 -07:00
|
|
|
scheduledTaskManager = new ScheduledTaskManager(instanceSettings);
|
2024-07-16 11:42:48 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
it('should throw when workflow timezone is invalid', () => {
|
|
|
|
expect(() =>
|
|
|
|
scheduledTaskManager.registerCron(
|
|
|
|
mock<Workflow>({ timezone: 'somewhere' }),
|
|
|
|
everyMinute,
|
|
|
|
onTick,
|
|
|
|
),
|
|
|
|
).toThrow('Invalid timezone.');
|
|
|
|
});
|
|
|
|
|
|
|
|
it('should throw when cron expression is invalid', () => {
|
|
|
|
expect(() =>
|
|
|
|
//@ts-expect-error invalid cron expression is a type-error
|
|
|
|
scheduledTaskManager.registerCron(workflow, 'invalid-cron-expression', onTick),
|
|
|
|
).toThrow();
|
|
|
|
});
|
|
|
|
|
|
|
|
it('should register valid CronJobs', async () => {
|
|
|
|
scheduledTaskManager.registerCron(workflow, everyMinute, onTick);
|
|
|
|
|
|
|
|
expect(onTick).not.toHaveBeenCalled();
|
|
|
|
jest.advanceTimersByTime(10 * 60 * 1000); // 10 minutes
|
|
|
|
expect(onTick).toHaveBeenCalledTimes(10);
|
|
|
|
});
|
|
|
|
|
2024-08-22 02:46:13 -07:00
|
|
|
it('should should not invoke on follower instances', async () => {
|
|
|
|
scheduledTaskManager = new ScheduledTaskManager(mock<InstanceSettings>({ isLeader: false }));
|
|
|
|
scheduledTaskManager.registerCron(workflow, everyMinute, onTick);
|
|
|
|
|
|
|
|
expect(onTick).not.toHaveBeenCalled();
|
|
|
|
jest.advanceTimersByTime(10 * 60 * 1000); // 10 minutes
|
|
|
|
expect(onTick).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
|
2024-07-16 11:42:48 -07:00
|
|
|
it('should deregister CronJobs for a workflow', async () => {
|
|
|
|
scheduledTaskManager.registerCron(workflow, everyMinute, onTick);
|
|
|
|
scheduledTaskManager.registerCron(workflow, everyMinute, onTick);
|
|
|
|
scheduledTaskManager.registerCron(workflow, everyMinute, onTick);
|
|
|
|
scheduledTaskManager.deregisterCrons(workflow.id);
|
|
|
|
|
|
|
|
expect(onTick).not.toHaveBeenCalled();
|
|
|
|
jest.advanceTimersByTime(10 * 60 * 1000); // 10 minutes
|
|
|
|
expect(onTick).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
});
|