0

Side Note: Basically this is a note for my own forgetful brain... I have crossed and solved this problem multiple times so this is for me to get my own solution back on my search results lol :D

Issue: When creating integration tests for my current aws event consumer implementation I've struggled with mocking out the sqs-consumer library.

Solution:

// Get the whole sqs-consumer package
let CONSUMER = require('sqs-consumer');

// mock the entire sqs-consumer package
jest.mock('sqs-consumer');


// at this point I have a reference to the library: CONSUMER
// and the library module functionality is completely mocked
// I want to be able to define and call functionality from the consumer class
// in my implementation i first call create, a static function
// from there I call the Consumer object methods which i'm going to mock here

CONSUMER.Consumer.create = jest.fn().mockReturnValue({
  emit: jest.fn().mockImplementation(() => console.log('emit')),
  on: jest.fn().mockImplementation(() => console.log('on')),
  once: jest.fn().mockImplementation(() => console.log('once')),
  start: jest.fn().mockImplementation(() => console.log('start')),
  stop: jest.fn().mockImplementation(() => console.log('stop')),
});

i tried various approaches and this was the best approach for my needs. I hope this helps someone not struggle as long as I did! Also if anyone has a better approach lets see it!

jen
  • 195
  • 1
  • 7
  • Show the code under test. How did you use `sqs-consumer`? – Lin Du Dec 05 '22 at 03:39
  • Im not specifically testing it as its an integration test and i'm just trying to remove the sqs-consumer dependency because in my service it is creating and starting consumers as a background process which is causing open handles in the integration tests @slideshowp2 – jen Dec 06 '22 at 13:44

1 Answers1

0

another way to mock in jest.setup.ts

jest.mock('sqs-consumer', () => ({
  Consumer: {
    create: jest.fn().mockReturnValue({
      emit: jest.fn().mockImplementation(() => {}),
      on: jest.fn().mockImplementation(() => {}),
      once: jest.fn().mockImplementation(() => {}),
      start: jest.fn().mockImplementation(() => {}),
      stop: jest.fn().mockImplementation(() => {}),
    }),
  },
}));
jen
  • 195
  • 1
  • 7