1

I am making a get request to an API using requestjs and then in the requestCallBack mapping the body to a custom json object. I am trying to test this code using Jest but no matter how I mock it, it doesn't seem to work

I have tried request.get.mockImplementation() and that seems to only mock the get and doesn't let me test the code in the callback

    await request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) })
    jest.mock('request')
    jest.mock('request-promise-native')

    import request from 'request-promise-native'

    test('test requestCallback code', async () => {
        // not sure how to test that bodyTransformer is called and is working
    }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Austin Mehmet
  • 448
  • 4
  • 13

1 Answers1

0

You can get the arguments a mock was called with using mockFn.mock.calls.

In this case request.get is a mock function (since the entire request-promise-native was auto-mocked), so you can use request.get.mock.calls to get the arguments it was called with. The third argument will be your callback, so you can retrieve it and then test it like this:

jest.mock('request-promise-native');

import request from 'request-promise-native';

test('test requestCallback code', () => {
  request.get('endpoint', requestOptions, (err, res, body) => { transformBodyContent(body) });

  const firstCallArgs = request.get.mock.calls[0];  // get the args the mock was called with
  const callback = firstCallArgs[2];  // callback is the third argument

  // test callback here
});
Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • This is awesome! Thanks Brian. Another question: how would I grab and test a parameter in that callback IE `(req, res, body) => { this.firstName = body.firstName }` When I use your code provided I seem to always get back undefined for body – Austin Mehmet Jan 11 '19 at 16:05
  • Figured it out Brian - just had to pass in the args I needed. Really appreciate the help. Thanks! – Austin Mehmet Jan 11 '19 at 16:37