I have a class MyCar which has a function let's say getAllCars().
export default class MyCar {
function getAllCars(){
try {
/**
* logic and query to dynamodb database to get all cars
* These Car objects will be fetched from db.
*/
const result = [Car, Car, Car, Car];
return result;
catch (error) {
if(error.code === 'ValidationException') {
throw error;
}
}
}
}
This function has logic to query the dynamodb table and return a paginated response.
In one of the scenario dynamodb throws a ValidationException. This exception is caught by the catch() block. I want to mock this ValidationException in my unit test case so that if this exception occurs, I can appropriately return a custom error message.
The returned exception object is this,
{
"message": "The provided starting key does not match the range key predicate",
"code": "ValidationException",
"time": {},
"requestId": "xxxx-xxxx-xxxx-xxxx-xxxx",
"statusCode": 400,
}
What I have done for now is this,
jest.spyOn(MyCar.prototype, 'getAllCars')
.mockImplementation(() => {
throw { code: 'ValidationException' };
});
and my expectation is below,
expect(async () => {
return myCar.getAllCars()
}).rejects.toHaveProperty('code', 'ValidationException');
What I want to do is, instead of throwing the object { code: 'ValidationException' } in the mockImplementation(), I want to throw the actual ValidationException from the dynamodb. Is there any way in which I can do so?
For other exception such as ItemNotFoundException, I can directly import it from @aws/dynamodb-data-mapper. Something like this,
import { ItemNotFoundException } from '@aws/dynamodb-data-mapper';
jest.spyOn(MyCar.prototype, 'getAllCars')
.mockImplementation(() => {
throw ItemNotFoundException;
});
It would be ideal if I could import the exception and mock it or find any package which would let me do so.
Here is a link of Exceptions for dynamodb Error Handling with DynamoDB