Hi I want to mock the response in Http Request function. I could not find anything on net, that states how we can mock a callback and pass it on to the function.
File 1: HTTPfile.ts
import https from 'https';
const putSampleDataAsync = (): Promise<string> => {
var options = {
host: 'sample.com',
path: '/upload',
method: 'PUT',
};
const body = [];
return new Promise(function (resolve, reject) {
var req = https.request(options, function (res) {
res.on('data', function (chunk) {
body.push(chunk);
});
res.on('end', function (chunk) {
body.push(chunk);
resolve(res.statusCode.toString());
});
});
req.on('error', function (error) {
reject(error);
});
req.write('some sample data in stringify Json format');
req.end();
});
};
File 2: HTTPfile.test.ts
import putSampleDataAsync from 'HTTPfile';
import https from 'https';
jest.mock('https');
describe('Mocking HTTP Calls Test', () => {
test('Success - ', () => {
(https.request as jest.Mock).mockImplementation((options, response) => {
console.log('How to mock ..!' + response);
return {
on: jest.fn(),
write: jest.fn(),
end: jest.fn(),
};
});
});
});
I kept the http.ts (with a simple mock of http.request as jest.fn) in mock folder in root of my application.
Here I want to mock response callback function which is getting passed as a parameter.