简体   繁体   中英

SOLUTION: How to mock sqs-consumer library in jest

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!

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(() => {}), }), }, }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM