I'm trying to write unit tests for a TypeScript class that calls DynamoDb. This is what I've got so far.
import {DataMapper, QueryIterator} from '@aws/dynamodb-data-mapper';
import DynamoDB = require("aws-sdk/clients/dynamodb");
jest.mock("aws-sdk/clients/dynamodb");
jest.mock("@aws/dynamodb-data-mapper");
describe("queryDynamoDb", () => {
    let myRepository = new MyRepository();
    const mockQueryCall = jest.fn();
    DataMapper.prototype.query = mockQueryCall;
   test("queriesDynamoDb", async () => {
        const mockQueryIterator = <jest.Mock<QueryIterator<DataObject>>>QueryIterator;
        mockQueryIterator.prototype.next.mockReturnValueOnce(getExpectedReturnObjectsValues())
        mockQueryCall.mockReturnValue(mockQueryIterator);
        let responseObjects = await myRepository.queryDynamoDb(testIdString);
        // Validate response Objects
   })
});
The method iterates through the response with a for...of loop, so I need the .next function to return.
To test the test, I added console.log(await queryIterator.next()); to my dynamoDb querying function. 
But when I try to run it, the response is:
TypeError: queryIterator.next is not a function
on that log line.
So, clearly mockQueryCall.mockReturnValue(mockQueryIterator); is either not doing its work and returning my mockQueryIterator, or const mockQueryIterator = <jest.Mock<QueryIterator<DataObject>>>QueryIterator; is not correctly applying type to the mockQueryIterator. But I don't know how to fix either of those things. 
After some trial and error, I came up with something that works.  It mocks the QueryIterator's Symbol.iterator function.
import {DataMapper, QueryIterator, StringToAnyObjectMap} from '@aws/dynamodb-data-mapper';
import createMockInstance from 'jest-create-mock-instance';
describe('alert service test', () => {
    test('find by user id', async () => {
        const mapper = createMockInstance(DataMapper);
        const qi: QueryIterator<StringToAnyObjectMap> = createMockInstance(QueryIterator);
        // @ts-ignore
        qi[Symbol.iterator] = jest.fn(() => [1, 2, 3].values());
        mapper.query.mockReturnValue(qi);
        // @ts-ignore any query arguments will do
        const results = mapper.query();
        const resultArray = [];
        for await (const o of results) {
            resultArray.push(o);
        }
        expect(resultArray).toEqual([1, 2, 3]);
    });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With