I have an issue which is blocking me from some time. So, I have the following code:
Publisher.js
import { logger } from "logger";
import retry from "async-retry";
import publishMessage from "./publishMessage";
import saveFailedEvent from "./saveFailedMessage";
export default function publishWithRetry({
message,
topicName,
connectionString,
retries,
minTimeout,
maxTimeout,
factor,
}) {
return retry(() => publishMessage({ message, topicName, connectionString }), {
retries,
minTimeout,
maxTimeout,
factor,
onRetry: (err, number) => {
logger.log(
"error",
"false",
`Retry number ${number}: Failed to send message`
);
if (number === retries) {
saveFailedEvent({ message, topicName });
logger.log(
"error",
"false",
"Retries exhausted. Event will be saved in <colllection name> collection"
);
}
},
});
}
SaveFailedMessage.js
import { logger } from "logger";
import FailedMessageModel from "../../models/FailedMessageModel";
async function saveFailedMessage({ message, topicName }) {
try {
const payload = message;
const eventError = {
eventName: payload.body.event_name,
publisher: payload.body.producer,
destination: topicName,
createdDateTime: Date.now(),
payload,
};
await FailedMessageModel.create(eventError);
} catch (err) {
logger.log(
"error",
"false",
`Failed to save FailedMessageModel in db${err}`,
"saveFailedMessage",
""
);
}
}
export default saveFailedMessage;
and my test file:
import { ServiceBusClient } from "@azure/service-bus";
import EventService from '../../src/index';
jest.mock('@azure/service-bus', () => {
return {
ServiceBusClient: jest.fn()
};
});
describe('Publish messages to azure service bus', () => {
const sbConnection =
"Endpoint=asdaasda";
const events = new EventService({
connection: sbConnection,
retries: 3,
minTimeout: 1000,
maxTimeout: 1000,
factor: 1,
});
it('should publish messages with success', async () => {
const sendMessages = jest.fn();
ServiceBusClient.mockImplementation(() => {
return {
createSender: jest.fn().mockReturnValue({
sendMessages,
close: jest.fn()
})
};
})
const message = {
body: {
message: "testing resiliance",
},
};
events.publish({ message, topicName: "event_topic" })
expect(sendMessages).toHaveBeenCalledWith(message)
});
it('should throw an error when publish message', async () => {
const sendMessages = jest.fn().mockImplementation(() => {
throw new Error('test error');
});
ServiceBusClient.mockImplementation(() => {
return {
createSender: jest.fn().mockReturnValue({
sendMessages,
close: jest.fn()
})
};
})
const message = {
body: {
message: "testing resiliance",
},
};
events.publish({ message, topicName: "event_topic" })
expect(sendMessages).toHaveBeenCalledWith(message)
});
});
The problem is that I'm having issues covering the saveFailedMessage which is Imported as saveFailedEvent
in Publisher.js . If somebody can help me a bit here, how should I write the test to cover this method also.
Aucun commentaire:
Enregistrer un commentaire