Last active
November 14, 2020 22:15
-
-
Save OssiPesonen/2e4927f2921daa06c93a8e476201e045 to your computer and use it in GitHub Desktop.
How Node.js mocking actually works
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWSMock = require('aws-sdk-mock'); | |
const AWS = require('aws-sdk'); | |
const expect = require('chai').expect; | |
describe('the module', () => { | |
it('should mock getItem from DynamoDB', async () => { | |
// Here we initiate the AWS.DynamoDB object before we call AWSMock | |
const dynamodb = new AWS.DynamoDB({ apiVersion: '2012-08-10' }); | |
AWSMock.setSDKInstance(AWS); | |
// Since the object already exists in memory, this doesn't work | |
AWSMock.mock('DynamoDB', 'getItem', (params, callback) => { | |
console.log('DynamoDB', 'getItem', 'mock called'); | |
callback(null, { pk: 'foo', sk: 'bar' }); | |
}); | |
let input = { TableName: '', Key: {} }; | |
// In here we will call the ACTUAL AWS SDK because it was initiated before the mock, making this unit test fail | |
const result = await dynamodb.getItem(input).promise(); | |
expect(result).to.eql({ pk: 'foo', sk: 'bar' }); | |
AWSMock.restore('DynamoDB'); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWSMock = require('aws-sdk-mock'); | |
const AWS = require('aws-sdk'); | |
const expect = require('chai').expect; | |
describe('the module', () => { | |
it('should mock getItem from DynamoDB', async () => { | |
AWSMock.setSDKInstance(AWS); | |
// Mocking DynamoDB.getItem() | |
AWSMock.mock('DynamoDB', 'getItem', (params, callback) => { | |
console.log('DynamoDB', 'getItem', 'mock called'); | |
callback(null, { pk: 'foo', sk: 'bar' }); | |
}); | |
let input = { TableName: '', Key: {} }; | |
// When calling AWS.DynamoDB node.js will use the mocked object | |
const dynamodb = new AWS.DynamoDB({ apiVersion: '2012-08-10' }); | |
const result = await dynamodb.getItem(input).promise(); | |
expect(result).to.eql({ pk: 'foo', sk: 'bar' }); | |
AWSMock.restore('DynamoDB'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment