timkindberg / jest-when

Jest support for mock argument-matched return values.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to mock with a callback?

Whoaa512 opened this issue · comments

I've got a mock which needs to call a callback. Currently this is not possible with your library.

As a workaround I've got this:

myMock.mockImplementationOnce((...args) => {
    expect(args).toEqual([
        'putObject',
        {
            Bucket: 'attachments',
            Key: 'some-guid',
            Expires: 900,
            ContentType: 'application/pdf',
        },
        expect.any(Function),
    ])

    const cb = _.last(args)

    cb(null, 'https://signed-url')
})

Ok so that behavior of calling a callback in jest is only possible via mockImplementation, since there is no convenient yield method like sinon.js has. So we essentially need to add mockImplementation to jest-when.

We could add new methods that worked like this:

when(mockFn).calledWith(expectedArgs).mockImplementation(mockImplFn)
when(mockFn).calledWith(expectedArgs).mockImplementationOnce(mockImplFn)

A PR for these additions would be appreciated.

Fixed by #10

Available in v2.2.0