diff options
author | eug-vs <eug-vs@keemail.me> | 2020-12-02 05:16:29 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-12-02 05:16:29 +0300 |
commit | ed24179795e821aa71fb4198bf072d19415741ee (patch) | |
tree | cd77f4a0b5a576ab9f35c9d9beff2d44674e5c91 | |
parent | 10433d9d37452ed453272e12acc6012c1c15229d (diff) | |
download | mongo-cronjob-ed24179795e821aa71fb4198bf072d19415741ee.tar.gz |
test: Scheduler
-rw-r--r-- | .mocharc.json | 3 | ||||
-rw-r--r-- | test/model.ts | 4 | ||||
-rw-r--r-- | test/scheduler.test.ts | 60 |
3 files changed, 65 insertions, 2 deletions
diff --git a/.mocharc.json b/.mocharc.json index dbf2db2..6511ecb 100644 --- a/.mocharc.json +++ b/.mocharc.json @@ -3,5 +3,6 @@ "chai/register-should", "ts-node/register", "test/utils/dbConnection.ts" - ] + ], + "timeout": 30000 } diff --git a/test/model.ts b/test/model.ts index 4d189dc..f8f76a6 100644 --- a/test/model.ts +++ b/test/model.ts @@ -1,10 +1,12 @@ import { Schema } from 'mongoose'; -import model from '../lib/event.model'; +import model, { Event } from '../lib/event.model'; interface Context { message: string; } +export type CustomEvent = Event<Context>; + const contextSchema = new Schema({ message: String }); diff --git a/test/scheduler.test.ts b/test/scheduler.test.ts new file mode 100644 index 0000000..ffcd623 --- /dev/null +++ b/test/scheduler.test.ts @@ -0,0 +1,60 @@ +import { expect } from 'chai'; +import Scheduler from '../lib/scheduler'; +import Model, { CustomEvent } from './model'; +import connection from './utils/dbConnection'; + +const sleep = async (time: number) => new Promise<void>(res => setTimeout(res, time)); + +describe('Scheduler', async () => { + let event: CustomEvent; + 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 () => { + connection.dropCollection('customevents'); + }); + + + it('Should run event', async () => { + // Wait until job is run + await new Promise<void>(res => { + scheduler.registerHandler('test', async (event: CustomEvent) => { + 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'); + }); +}); |