Node.js/Jest

[AWS-CDK] How to Mock AWS-CDK, DynamoDB

brightlightkim 2022. 4. 19. 08:12

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

 

GitHub - mrdulin/jest-codelab: Learning JavaScript Test Framework - Jestjs v24.x.x by examples

Learning JavaScript Test Framework - Jestjs v24.x.x by examples - GitHub - mrdulin/jest-codelab: Learning JavaScript Test Framework - Jestjs v24.x.x by examples

github.com

from https://stackoverflow.com/questions/64564233/how-to-mock-aws-dynamodb-in-jest-for-serverless-nodejs-lambda

 

How to mock AWS DynamoDB in Jest for Serverless Nodejs Lambda?

I wrote a lambda as follows. handler.js const aws = require('aws-sdk'); const dynamoDb = new aws.DynamoDB.DocumentClient(); const testHandler = async event => { // some code // ... const ...

stackoverflow.com