'NestJS Jest spy a callback function

So I have a class which has a function. Inside this function, I execute another function from a library's class object which has a callback function. Inside that callback function, there's a method that I need to spy into. Is there any way to do that? Here's the rough detail:

export class Consume {
  private readonly consumer: Consumer; // class from the library
  private readonly randomService: RandomService; // class that it's method I want to spy on

  constructor() {
    this.consumer = new Consumer();
    this.randomService = new RandomService();
  }

  consume(): void {
    this.consumer.consume(async data => {
      ...
      this.randomService.doSomething('withParam'); // I need to spy here on this method
      ...
    })
  }
}

I've tried mocking, but don't seem to work, here's what I have tried:

it('should do something', () => {
  const consumerSpy = jest.spyOn(consumer, 'consume');
  consumerSpy.mockImplementation(cb => {
    cb(['data1', 'data2'])
  }); // mocking the library's function
  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

and also this:

it('should do something', () => {
  jest.mock('path/to/consume-class', () => {
    consume: jest.fn()
  }); // mocking Consume's consume function

  consume.consume(); // calling consume function from Consume class above

  const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
  expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
});

Any help would be appreciated! :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source