aboutsummaryrefslogtreecommitdiff
path: root/test/scheduler.test.ts
blob: 1736ed47b084817b22532dc636a789a6a57b2462 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { expect } from 'chai';
import Scheduler from '../lib/scheduler';
import client, { Event } from './client';

const Model = client.Event;
const sleep = async (time: number) => new Promise<void>(res => setTimeout(res, time));

describe('Scheduler', async () => {
  let event: Event;
  let scheduler: Scheduler;

  beforeEach(() => {
    scheduler = new Scheduler(Model);
  });

  afterEach(() => {
    scheduler.stopPolling();
  });

  before(async () => {
    event = await Model.create({
      type: 'test',
      schedule: '*/15 * * * * *', // Every 15 seconds
      context: {
        message: 'Hello, world!'
      },
    });
  });

  after(async () => {
    client.connection.dropCollection('events');
  });


  it('Should run event', async () => {
    // Wait until job is run
    await new Promise<void>(res => {
      scheduler.registerHandler('test', async (event: Event) => {
        await sleep(2000);
        await event.log(event.context.message)
        res();
      });
    });

    // Wait for status to change
    await sleep(100);

    const updatedEvent = await Model.findOne();
    expect(updatedEvent).to.have.property('status').equal('complete');
  });


  it('Should fail an event if no handler is present', async () => {
    await sleep(25000);

    const updatedEvent = await Model.findOne();
    expect(updatedEvent).to.have.property('status').equal('failed');
    expect(updatedEvent).to.have.property('error').equal('Error: No handler found');
  });
});