Thursday 18 March 2021

Mock Lambda callback in Jest? (Cannot read property body of undefined)

I'm trying to unit test a lambda function but can't figure out how to mock the lambda callback so it stops code execution. The callback I mock up is being called, which in the case of a lambda would immediately return the response. In my unit tests though, it continues executing code and I get the error:

TypeError: Cannot read property 'body' of undefined

I'm relatively new to Jest so not sure how to proceed.

example.js (lambda code)

// dependencies
const got = require('got');

// lambda handler
const example = async (event, context, callback) => {
  // message placeholder
  let message;

  // set request options
  const gotOptions = {
    json: {
      process: event.process
    },
    responseType: 'json'
  };

  // http response data
  const res = await got.post('https://some.url/api/process', gotOptions).catch((error) => {
    message = 'error calling process';

    // log and return the error
    console.log(message, error);
    callback(message);
  });

  // res.body is causing the error in the test since
  // this code still executes after callbacks triggered
  message = `Process ${event.process} is: ${res.body.active}`;


  callback(null, message);
};


// export example
exports.example = example;

example.test.js (unit test code)

// get the lib we want to test
const example = require('./example');

// setup mocks
jest.mock('got');

// mock our lambda callback
const callback = jest.fn();


// import the modules we want to mock
const got = require('got');


// set default event
let event = {
  process: 1
};

// set default context
const context = {};


// run before each test
beforeEach(() => {
  // set default got.post response
  got.post.mockReturnValue(Promise.resolve({
    body: {
      active: true
    }
  }));
});

// test artifact api
describe('[example]', () => {
  ...other tests that pass...

  test('error calling process api', async () => {
    let error = 'error calling process';

    // set got mock response for this test to error
    got.post.mockReturnValue(Promise.reject(error));

    // function we want to test w/ mock data
    await example.example(event, context, callback);

    // test our callback function to see if it matches our desired expectedResponse
    expect(callback).toHaveBeenCalledWith(error);
  });
});


from Mock Lambda callback in Jest? (Cannot read property body of undefined)

No comments:

Post a Comment