You could use jest.mock(moduleName, factory, options) to mock aws-sdk module manually.
E.g.
handler.js:
const aws = require('aws-sdk');
const dynamoDb = new aws.DynamoDB.DocumentClient();
const promisify = (foo) =>
new Promise((resolve, reject) => {
foo((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
const getUser = (userId) =>
promisify((callback) =>
dynamoDb.get(
{
TableName: 'test-table',
Key: {
PK: `${userId}`,
SK: `${userId}`,
},
},
callback,
),
).then((user) => {
console.log(`Retrieved user: ${userId}`);
return user;
});
module.exports = { getUser };
handler.test.js:
const aws = require('aws-sdk');
const { getUser } = require('./handler');
jest.mock('aws-sdk', () => {
const mDocumentClient = { get: jest.fn() };
const mDynamoDB = { DocumentClient: jest.fn(() => mDocumentClient) };
return { DynamoDB: mDynamoDB };
});
const mDynamoDb = new aws.DynamoDB.DocumentClient();
describe('64564233', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should get user', async () => {
const mResult = { name: 'teresa teng' };
mDynamoDb.get.mockImplementationOnce((_, callback) => callback(null, mResult));
const actual = await getUser(1);
expect(actual).toEqual({ name: 'teresa teng' });
expect(mDynamoDb.get).toBeCalledWith(
{
TableName: 'test-table',
Key: {
PK: '1',
SK: '1',
},
},
expect.any(Function),
);
});
it('should handler error', async () => {
const mError = new Error('network');
mDynamoDb.get.mockImplementationOnce((_, callback) => callback(mError));
await expect(getUser(1)).rejects.toThrowError('network');
expect(mDynamoDb.get).toBeCalledWith(
{
TableName: 'test-table',
Key: {
PK: '1',
SK: '1',
},
},
expect.any(Function),
);
});
});
unit test result:
PASS src/stackoverflow/64564233/handler.test.js (14.929s)
64564233
✓ should get user (23ms)
✓ should handler error (3ms)
console.log src/stackoverflow/64564233/handler.js:433
Retrieved user: 1
------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
handler.js | 100 | 100 | 100 | 100 | |
------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 17.435s
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/64564233
'Node.js > Jest' 카테고리의 다른 글
[Jest] toBeTruthy() (0) | 2022.04.19 |
---|---|
[Jest] How to set up Debug in Visual Studio Code? (0) | 2022.04.16 |
[Jest] Sample Axios Mock Function (0) | 2022.04.16 |
[Jest] set, clear and reset mock/spy/stub implementation (0) | 2022.04.16 |
[Jest] Jest Mock Functions (0) | 2022.04.15 |