UNPKG

node-sidekiq-client

Version:
106 lines (84 loc) 3.18 kB
// tests/sidekiq_client.test.ts import { createClient, RedisClientType } from 'redis'; import { SidekiqClient, JobPayload } from '../src/index'; import { jest } from '@jest/globals'; function assertJidFormat(jid: string) { expect(typeof jid).toBe('string'); expect(jid).toMatch(/^[0-9a-f]{24}$/); } describe('SidekiqClient (TypeScript)', () => { let redisClient: RedisClientType; let sidekiq: SidekiqClient; beforeAll(async () => { redisClient = createClient({ url: 'redis://redis:6379/0' }); await redisClient.connect(); }); afterAll(async () => { await redisClient.quit(); }); beforeEach(async () => { await redisClient.flushDb(); sidekiq = new SidekiqClient(redisClient); }); afterEach(async () => { await redisClient.flushDb(); }); it('performAsync enqueues a job', async () => { const queue = 'default'; const jobClass = 'MyWorker'; const args = [1, 2, 3]; const jid = await sidekiq.performAsync(queue, jobClass, args); assertJidFormat(jid); const length = await redisClient.lLen(`queue:${queue}`); expect(length).toBe(1); const raw = await redisClient.lPop(`queue:${queue}`); expect(raw).not.toBeNull(); const job: JobPayload = JSON.parse(raw!); expect(job.class).toBe(jobClass); expect(job.queue).toBe(queue); expect(job.args).toEqual(args); expect(job.created_at).toBeDefined(); expect(job.enqueued_at).toBeDefined(); assertJidFormat(job.jid); }); it('performIn schedules a job after a delay', async () => { const queue = 'delayed'; const jobClass = 'DelayedJob'; const args = ['x']; const seconds = 2; const before = Date.now(); const jid = await sidekiq.performIn(seconds, queue, jobClass, args); assertJidFormat(jid); const zcount = await redisClient.zCard('schedule'); expect(zcount).toBe(1); const { value: member, score } = (await redisClient.zRangeWithScores('schedule', 0, 0))[0]; const job: JobPayload = JSON.parse(member); expect(job.class).toBe(jobClass); expect(job.queue).toBe(queue); expect(job.args).toEqual(args); expect(job.created_at).toBeDefined(); expect(job.enqueued_at).toBeUndefined(); assertJidFormat(job.jid); // Score should be ≈ before + seconds expect(Math.abs(score - (before + seconds))).toBeLessThan(1); }); it('performAt schedules a job at an exact time', async () => { const queue = 'scheduled'; const jobClass = 'SpecificTimeJob'; const args = ['run_at']; const timestamp = Date.now() + 3000; const jid = await sidekiq.performAt(timestamp, queue, jobClass, args); assertJidFormat(jid); const zcount = await redisClient.zCard('schedule'); expect(zcount).toBe(1); const { value: member, score } = (await redisClient.zRangeWithScores('schedule', 0, 0))[0]; const job: JobPayload = JSON.parse(member); expect(job.class).toBe(jobClass); expect(job.queue).toBe(queue); expect(job.args).toEqual(args); expect(job.created_at).toBeDefined(); expect(job.enqueued_at).toBeUndefined(); assertJidFormat(job.jid); expect(score).toBe(timestamp/1000); }); });