Skip to content

Commit

Permalink
Current publish and subscribe unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinLemon112 committed Aug 18, 2024
1 parent 1bd771f commit 5bd1022
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
9 changes: 5 additions & 4 deletions src/notification/publish/publish.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mqtt, { MqttClient, IClientPublishOptions, PacketCallback, DoneCallback }
import express from 'express';
import request from 'supertest';
import { connectToMongoDB } from './db';
import { log, error } from "console";

jest.mock('mqtt');
jest.mock('./db');
Expand Down Expand Up @@ -68,10 +69,10 @@ describe('Publish Service', () => {
};

client.on('connect', () => {
console.log('Broker connected');
log('Broker connected');
client.publish(topic, JSON.stringify(event), {}, (err) => {
if (err) {
console.error(`Error publishing message: ${err}`);
error(`Error publishing message: ${err}`);
res.status(500).json({ error: 'Internal Server Error' });
} else {
client.end();
Expand All @@ -81,7 +82,7 @@ describe('Publish Service', () => {
});

client.on('error', (error: Error) => {
console.log(error);
log(error);
res.status(500).json({ error: 'Internal Server Error' });
});
});
Expand Down Expand Up @@ -116,5 +117,5 @@ describe('Publish Service', () => {

expect(response.status).toBe(500);
expect(response.body).toEqual({ error: 'Internal Server Error' });
}, 10000);
}, 5000);
});
38 changes: 23 additions & 15 deletions src/notification/subscribe/subscribe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import mqtt, { MqttClient } from 'mqtt';
import request from 'supertest';
import express from 'express';
import { connectToMongoDB } from './db';
import { log } from "console";

jest.mock('mqtt');
jest.mock('./db');

// Helper function to create a mock MQTT client
const mockClient = (): Partial<MqttClient> => {
const client: Partial<MqttClient> = {
on: jest.fn(),
Expand All @@ -28,7 +30,7 @@ describe('Subscribe Service', () => {

beforeEach(() => {
app = express();

const subscribeRouter = express.Router();

subscribeRouter.get('/status', (req, res) => {
Expand All @@ -41,14 +43,21 @@ describe('Subscribe Service', () => {
(mqtt.connect as jest.Mock).mockReturnValue(client);
(connectToMongoDB as jest.Mock).mockResolvedValue(undefined);

// Set up the event handler mock
// Ensure the MQTT client code is initialized
// Require or invoke the module that initializes the MQTT client
// For example:
// require('./path/to/your/mqtt-setup'); // Adjust path as needed

// Debugging: Check the number of connectMock calls
const connectMock = mqtt.connect as jest.Mock;
log('connectMock call count:', connectMock.mock.calls.length); // Debugging: Check the number of connect calls

const mockClientInstance = connectMock.mock.results[0]?.value as Partial<MqttClient>;

if (mockClientInstance) {
(mockClientInstance.on as jest.Mock).mockImplementation((event: string, handler: (...args: any[]) => void) => {
if (event === 'message') {
// Directly call the handler with test data
log('Mock on handler triggered'); // Debugging: Check if this line is executed
handler('test-topic', Buffer.from('test-message'));
}
return mockClientInstance as MqttClient;
Expand All @@ -68,30 +77,29 @@ describe('Subscribe Service', () => {
});

it('should log messages received from the broker', () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); // Mock implementation to avoid actual logging
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});

// Simulate message reception
// Ensure the MQTT client is set up and used
const connectMock = mqtt.connect as jest.Mock;
log('connectMock call count:', connectMock.mock.calls.length); // Debugging: Check the number of connect calls

const mockClientInstance = connectMock.mock.results[0]?.value as Partial<MqttClient>;

if (mockClientInstance && mockClientInstance.on) {
log('mockClientInstance.on:', mockClientInstance.on); // Debugging: Check the on method

const messageHandler = (mockClientInstance.on as jest.Mock).mock.calls.find(([event]) => event === 'message')?.[1];
if (messageHandler) {
messageHandler('test-topic', Buffer.from('test-message'));
}
}

// Debugging: Output the actual calls to `console.log`
console.log('logSpy calls:', logSpy.mock.calls); // Log all calls to console.log for inspection
const expectedMessage = 'Received message from topic test-topic: test-message';
const actualCalls = logSpy.mock.calls.map((call: any[]) => call.join(' '));

// Flatten the logged calls for easier inspection
const actualCalls = logSpy.mock.calls.map(call => call[0]);
console.log('Actual calls to console.log:', actualCalls); // Print actual calls for debugging
log('Actual calls to log:', actualCalls); // Debugging output
expect(actualCalls).toContain(expectedMessage);

// Check if expected message is among the logged calls
const expectedMessage = 'Received message from topic test-topic: test-message';
expect(actualCalls).toContain(expectedMessage); // Check if expected message is among the logged calls

logSpy.mockRestore(); // Restore original implementation after test
logSpy.mockRestore();
});
});

0 comments on commit 5bd1022

Please sign in to comment.