Jest 25.3.0
I am trying to mock DynamoDB dependency in my unit tests as follows:
const { findById } = require('./mymodule');
const mockDynamoDB = { getItem: jest.fn() };
jest.mock('aws-sdk', () => ({
DynamoDB: jest.fn(() => mockDynamoDB)
}));
describe('.', () => {
it('..', () => {
findById('test');
expect(mockDynamoDB.getItem).toBeCalledWith({
TableName: 'table-name',
Key: {
id: { S: 'test' }
}
});
});
});
Unfortunately, when I do that, I get the following error:
ReferenceError: Cannot access 'mockDynamoDB' before initialization
Strangely, if I do this, I can avoid the ReferenceError
:
const mockGetItem = { promise: jest.fn() };
jest.mock('aws-sdk', () => ({
DynamoDB: jest.fn(() => ({
getItem: jest.fn(() => mockGetItem)
})
}));
but this doesn't suit my test, as I can't validate the params passed to the getItem
function.
The actual code under test is fairly simple, it looks something like this:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
const toRecord = (item) => ({
id: item.id.S,
name: item.name.S
});
const findById = (id) => (
dynamodb.getItem({
TableName: 'table-name',
Key: {
id: { S: id }
}
}).promise()
.then(result => toRecord(result.Item))
.catch(error => console.log(error)
);
module.exports = {
findById
}
If anyone has seen this before, or can shed some light on why the first example fails while the second works, it would really help me out. Thank you.