Skip to content

Commit

Permalink
email worker + job test
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 21, 2023
1 parent b9e70da commit 3314030
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 35 deletions.
39 changes: 39 additions & 0 deletions __test__/jobs/email.job.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { type Job } from 'bullmq';
import emailJob from '../../src/jobs/email.job';

describe('emailJob', () => {
let consoleLogSpy: jest.SpyInstance;
let consoleErrorSpy: jest.SpyInstance;

beforeEach(() => {
consoleLogSpy = jest.spyOn(console, 'log');
consoleErrorSpy = jest.spyOn(console, 'error');
});

afterEach(() => {
consoleLogSpy.mockRestore();
consoleErrorSpy.mockRestore();
});

it('should process email job successfully', async () => {
const jobData = {
to: '[email protected]',
subject: 'Test Subject',
body: 'Test Body',
};

const job: Partial<Job> = {
id: 'jobId',
data: jobData,
name: 'emailJob',
};

await emailJob(job as Job);

expect(consoleLogSpy).toHaveBeenCalledWith(`Sending email to ${jobData.to}: ${jobData.subject}`);
expect(consoleLogSpy).toHaveBeenCalledWith('Body:', jobData.body);
expect(consoleLogSpy).toHaveBeenCalledWith('Email sent successfully');
expect(consoleErrorSpy).not.toHaveBeenCalled();
});

});
28 changes: 28 additions & 0 deletions __test__/workers/email.worker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Worker } from 'bullmq'
import { emailQueue } from '../../src/queues';
import connection from '../../src/queues/connection';

jest.mock('bullmq', () => ({
...jest.requireActual("bullmq"),
Worker: jest.fn().mockImplementation((queueName, processingFunction, options) => {
const workerMock = {
on: jest.fn(),
};
return workerMock;
}),
}));

describe('email.worker', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should create a new BullMQ worker for emailQueue', async () => {
require('../../src/workers/email.worker')
expect(Worker).toHaveBeenCalledWith(
emailQueue.name,
expect.any(Function),
{ connection }
);
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "env-cmd nodemon ./src/index.ts",
"test": "env-cmd jest --coverage --silent",
"test": "env-cmd jest --coverage",
"prettier": "npx prettier --write .",
"lint": "npx eslint ."
},
Expand Down
23 changes: 23 additions & 0 deletions src/jobs/email.job.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import { type Job } from 'bullmq';

const emailJob = async (job: Job): Promise<void> => {
// Define the processing logic for email jobs
const { to, subject, body } = job.data; // Assuming the job data contains the recipient, subject, and body of the email

try {
// Perform email processing logic here
console.log(`Sending email to ${to}: ${subject}`);
console.log('Body:', body);

// Simulating email sending time
await new Promise((resolve) => setTimeout(resolve, 2000));

console.log('Email sent successfully');
} catch (error) {
console.error('Error processing email:', error);
throw new Error('Failed to process email'); // Throw an error if email processing fails
}
}

export default emailJob
36 changes: 2 additions & 34 deletions src/workers/email.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,9 @@
import { Worker } from 'bullmq';
import { emailQueue } from '../queues'; // Assuming you have already defined the emailQueue
import connection from '../queues/connection';
import emailJob from '../jobs/email.job';

// Create a new BullMQ worker instance for emailQueue
const emailWorker = new Worker(emailQueue.name, async (job) => {
// Define the processing logic for email jobs
const { to, subject, body } = job.data; // Assuming the job data contains the recipient, subject, and body of the email

try {
// Perform email processing logic here
console.log(`Sending email to ${to}: ${subject}`);
console.log('Body:', body);

// Simulating email sending time
await new Promise((resolve) => setTimeout(resolve, 2000));

console.log('Email sent successfully');
} catch (error) {
console.error('Error processing email:', error);
throw new Error('Failed to process email'); // Throw an error if email processing fails
}
}, { connection });

emailWorker.on('failed', (job, err) => {
if (job !== undefined) {
console.error(`Job ${job.id} failed with error:`, err);
} else {
console.error('The job was undefined.')
}
});

emailWorker.on('completed', (job) => {
console.log(`Job ${job.id} completed successfully`);
});

emailWorker.on('error', (error) => {
console.error('Worker error:', error);
});
const emailWorker = new Worker(emailQueue.name, emailJob, { connection });

export default emailWorker

0 comments on commit 3314030

Please sign in to comment.