-1

I am using npm request, How to mock request.post I need to test the error scenario, statuscode not 200 scenario and the success flow.

1 request.post(reqObject, (error: Error, response: any, body: any) => {
2     if (error) { return reject(error); }
3     if (response.statusCode !== 200) {
4         return reject('Invalid status code <' + response.statusCode + '>');
5     }
6     return resolve(JSON.parse(body));
7 });
Bikesh M
  • 8,163
  • 6
  • 40
  • 52
  • I would recommend _not_ mocking things you don't own, like request. That way lies making your mock ever-more-complicated (see e.g. https://stackoverflow.com/a/65130857/3001761) as you use more of the interface, or even finding out that you're wrong about how to use it (see e.g. https://stackoverflow.com/a/65627662/3001761). Introduce a facade to mock, or use something like [`msw`](https://mswjs.io/) or [`nock`](https://www.npmjs.com/package/nock) to test at the transport layer. – jonrsharpe Mar 10 '21 at 09:39

1 Answers1

2

The request object can be mocked by jest.mock('request').

Something like this:

const request = require("request");
jest.mock('request', () => {
    return {
        post: () => { 
            console.log("mocked"); 
            // or something like jest.fn()
        }
    };
});

test('test description', () => {
    // request.post within fetchData has been mocked
    // await fetchData(); 
});

lastr2d2
  • 3,604
  • 2
  • 22
  • 37
  • thanks @lastr2d2 If I mock the post how can I test How can I test line number 2 to 6 ? – Bikesh M Mar 10 '21 at 06:26
  • 1
    You would define the parameters to the post mock to include (and subsequently call) the callback with values you want to test. – mhodges Mar 10 '21 at 06:30
  • 1
    an example mock function here `post: (req, callback) => { let err = null; let response = {statusCode: 200}; let body = {}; callback(err, response, body); }` – lastr2d2 Mar 10 '21 at 06:50