timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
738 stars 39 forks source link

Not working for mocked class method with callback #45

Closed pedrovieira closed 4 years ago

pedrovieira commented 4 years ago

Hi all, I recently started using this library but I'm not getting it to work with a mocked class method that receives a callback in one paramater.

Here's an example code (I'm using ts-jest here for the mocked()):

import { when } from 'jest-when';
import ExtensionStorage from '../src/extension-storage';

jest.mock('../src/extension-storage');

it('test', (done) => {
    const storage = new ExtensionStorage();
    when(mocked(storage.getSettings))
      .calledWith(expect.any(String), expect.anything)
      .mockImplementation((key, callback) => {
        callback('a');
      });

    storage.getSettings('', (val) => {
      expect(val).not.toBeNull(); // <---
      done();
    });
});

Where ExtensionStorage.getSettings is of type (key: string, callback: (settings: string | null) => void): void. In this case, the highlight line is never called. However, if I use the default way without jest-when, it works:

const storage = new ExtensionStorage();
mocked(storage.getSettings).mockImplementation((key, callback) => callback('test'));
storage.getSettings('', (val) => {
   expect(val).not.toBeNull(); // <---
   done();
});

Any ideas? Thanks!

pedrovieira commented 4 years ago

I've found the culprit! Looks like jest-when doesn't play well with expect.anything. I've since changed it to expect.any(Function) and it's working now

pedrovieira commented 4 years ago

Nevermind, my lack of sleep made me completely miss the fact that I was using expect.anything instead of expect.anything()

Well, consider this "issue" as a way to wish you all a great weekend 😁