I am putting in some basic unit tests for my usage of AWS DynamoDB. I have the happy path tests running, however I'm now wanting to test the catch block which will need me to throw an error from part of the process, and I'm wondering how I can alter my existing code to do this.
Is it possible to the toggle the mocked response from being a proper response to an error?
db.ts:
export const getData = async () => {
const command = new GetItemCommand({ ... });
try {
return await client.send(command);
} catch (err) {
throw new Error(`some error here`);
}
};
db.unit.ts:
jest.mock('@aws-sdk/client-dynamodb', () => ({
GetItemCommand: jest.fn(() => true),
DynamoDBClient: jest.fn(() => ({ send: jest.fn(() => 'get success') })),
}));
it('should get from db', async () => {
const res = await getData();
expect(res).toBe('get success');
});
it('should throw error when getting from db', async () => {
const res = await getData();
expect(res).toThrow('Some error thrown'); // Will be false as the mock always returns the 'get success'
});
I attempted to follow how to change jest mock function return value in each test? but it seemed like I couldn't get it working as they had, and in fact my previously working tests have now started failing.
import {GetItemCommand, UpdateItemCommand, DynamoDBClient} from '@aws-sdk/client-dynamodb';
jest.mock('@aws-sdk/client-dynamodb', () => ({
GetItemCommand: jest.fn(),
DynamoDBClient: jest.fn(() => ({ send: jest.fn(() => 'get success') })),
}));
it('should put things in db', async () => {
UpdateItemCommand.mockReturnValueOnce(true);
const res = await getResults();
expect(res).toBe('get success');
});
In the above, my IDE is complaining about UpdateItemCommand.mockReturnValueOnce(true) stating that
Property mockReturnValueOnce does not exist on type typeof UpdateItemCommand
jest.fn()object, e.g. by importing it, then can call the usual methods to control how it responds to interaction.UpdateItemCommandindeed does not have amockReturnValueOncemethod, so the compiler needs to know that's a mocked version of it.UpdateItemCommandisn't a mock function either...)