Skip to content

Commit

Permalink
add scheduler tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mfornos committed Oct 24, 2023
1 parent 7edae9c commit abf1808
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 0 deletions.
100 changes: 100 additions & 0 deletions src/services/persistence/scheduler.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { jest } from '@jest/globals';

import { MemoryLevel as Level } from 'memory-level';

import { _config, _log } from '../../test/services';
import { Scheduler } from './scheduler';

jest.useFakeTimers();

describe('scheduler service', () => {
let scheduler: Scheduler;
let db : Level;
let now: any;

beforeEach(() => {
db = new Level();
scheduler = new Scheduler(_log, db, {
schedulerFrequency: 500,
scheduler: true
});
now = jest.spyOn(Date, 'now')
.mockImplementation(() => 0);
});

afterEach(() => {
now.mockRestore();
});

it('should schedule and execute a task', async () => {
const ok = jest.fn();
scheduler.start();
scheduler.on('task', ok);

await scheduler.schedule({
key: new Date(Date.now()).toISOString() + 'a',
type: 'task',
task: {}
});

expect((await scheduler.allTaskTimes()).length).toBe(1);

now.mockImplementation(() => 1000);
jest.advanceTimersByTime(1000);

await scheduler.stop();

expect(ok).toBeCalled();
});

it('should remove a task', async () => {
const key = new Date(Date.now()).toISOString() + 'a';

await scheduler.schedule({
key,
type: 'task',
task: {}
});

expect((await scheduler.allTaskTimes()).length).toBe(1);

await scheduler.remove(key);

expect((await scheduler.allTaskTimes()).length).toBe(0);
});

it('should schedule and execute due tasks', async () => {
const ok = jest.fn();
scheduler.start();
scheduler.on('task', ok);

const time = Date.now();

await scheduler.schedule(
{
key: new Date(time).toISOString() + 'a',
type: 'task',
task: {}
},
{
key: new Date(time + 100).toISOString() + 'b',
type: 'task',
task: {}
},
{
key: new Date(time + 2000).toISOString() + 'c',
type: 'task',
task: {}
}
);

expect((await scheduler.allTaskTimes()).length).toBe(3);

now.mockImplementation(() => 1000);
jest.advanceTimersByTime(1000);

await scheduler.stop();

expect(ok).toBeCalledTimes(2);
});
});
4 changes: 4 additions & 0 deletions src/services/persistence/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export class Scheduler extends Stream.EventEmitter {
await batch.write();
}

async remove(key: string) {
await this.#tasks.del(key);
}

async allTaskTimes() {
return await this.#tasks.keys().all();
}
Expand Down

0 comments on commit abf1808

Please sign in to comment.