Jest mockImplementation errors when mocking aws-sdk top level functions

Viewed 1056

The code to be tested is as follows.

handler.js

const aws = require('aws-sdk');

const eventBridge = new aws.EventBridge();

const testHandler = async event => {
  // some code
  // ...
  await sendEvent(data)
  // ...
  // some code
}


const promisify = foo => new Promise((resolve, reject) => {
  foo((error, result) => {
    if (error) {
      reject(error)
    } else {
      resolve(result)
    }
  })
})

const sendEvent = (data) => promisify(callback =>
  eventBridge.putEvents({
    Entries: [
      {
        Detail: JSON.stringify({
          'data': data,
        }),
        DetailType: 'test-detail-type',
        EventBusName: 'test-eventbus',
        Resources: [],
        Source: 'event.source.test'
      }
    ]
  }, callback))
  .then((result) => 
    console.log('Event is emitted.')
  )

module.exports = {
  testHandler: testHandler,
  sendEvent: sendEvent
}

My test is as follows

handler.test.js

const handler = require('./handler');
const aws = require('aws-sdk')

jest.mock("aws-sdk");

aws.EventBridge.prototype.putEvents.mockImplementation((_, cb) => {
  cb(null, {});
});

describe('test sendEvent', () => {

  beforeEach(() => {
    jest.resetModules()
  });

  test('send event success', async () => {
    const data = 'sample'
    const result = await handler.sendEvent(data);
    expect(result).toBeUndefined();
  });
});

The error complains the mockImplementation is called by an undefined putEvents

TypeError: Cannot read property 'mockImplementation' of undefined

error

TypeError: Cannot read property 'mockImplementation' of undefined

    > 14 | aws.EventBridge.prototype.putEvents.mockImplementation((_, cb) => {
         |                                     ^
      15 |   cb(null, {});
      16 | });
      17 |

However, if I use jest.fn() directly without the mockImplementation as follows, the test passes without errors.

aws.EventBridge.prototype.putEvents = jest.fn((_, cb) => {cb(null, {})}) 

Just wondering if the behaviour is it supposed to be or I'm understanding anything wrong?

0 Answers
Related