javascriptjestjsrestifyrequest-promiserequestjs

How do you mock/test requestjs requestcallback with Jest


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
    }

Solution

  • 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
    });