I have an azure function like so (not the actual function, just a representation is given below)
import { AzureFunction, Context, HttpRequest } from '@azure/functions'
import { ServiceBusClient, isServiceBusError } from '@azure/service-bus'
const serviceBusClient = new ServiceBusClient(clientConnectionString)
const sender = serviceBusClient.createSender(topicName)
const func: AzureFunction = async function (
context: Context,
req: HttpRequest
): Promise<void> {
try {
sender.sendMessages({ body: {a:"a",b:"b",c:"c" })
}
catch (error: unknown) {
if (isServiceBusError(error)) {
message = `This is the error message ${error.message} with the reason ${error.code}`
context.log.error(`Error Message: ${message}`)
} else {
context.log.error(`Error Message: Error Encountered`)
}
}
}
How do to test if the code in the catch
block is working properly?
Specifically, how do I throw a ServiceBusError
to test that it is caught and appropriate error message is logged?
Can any one guide or provide hint on how to proceed?
Update
I already have the following code to mock the service bus & also to check is an error is a Service bus error
. However, I am not able to understand how I can have this function to mock both a 'good' case (message sent successfully) and a 'bad' case (where ServiceBusError
is thrown`).
jest.mock('@azure/service-bus', () => {
return {
isServiceBusError: jest.fn().mockImplementation((err: unknown) => {
if (err === ServiceBusError) {
return true
} else return false
}),
ServiceBusClient: jest.fn().mockImplementation(() => {
return {
createSender: jest.fn().mockImplementation(() => {
return {
sendMessages: mockSendMessages,
}
}),
}
}),
}
})
I test is like so
test('Bad case: Empty Data', async () => {
const emptyData = {}
const wrongRequest = {
query: {},
body: emptyData,
}
// Action
await func(context, wrongRequest)
expect(mockSendMessages).toHaveBeenCalledTimes(0)
})
How to use the mock
to throw the error is where I am getting confused (fyi, the above test case works just fine).