title: NestJS Jest spy a callback function
body: <p>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:</p>
  <pre class="lang-js prettyprint-override"><code>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 =&gt; {
        ...
        this.randomService.doSomething('withParam'); // I need to spy here on this method
        ...
      })
    }
  }
  </code></pre>
  <p>I've tried mocking, but don't seem to work, here's what I have tried:</p>
  <pre class="lang-js prettyprint-override"><code>it('should do something', () =&gt; {
    const consumerSpy = jest.spyOn(consumer, 'consume');
    consumerSpy.mockImplementation(cb =&gt; {
      cb(['data1', 'data2'])
    }); // mocking the library's function
    const randomServiceSpy = jest.spyOn(randomService, 'doSomething')
    expect(randomServiceSpy).toBeCalledTimes(1); // Number of times called: 0 returned
  });
  </code></pre>
  <p>and also this:</p>
  <pre class="lang-js prettyprint-override"><code>it('should do something', () =&gt; {
    jest.mock('path/to/consume-class', () =&gt; {
      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
  });
  </code></pre>
  <p>Any help would be appreciated! :)</p>