admin管理员组文章数量:1356927
I have an external POST API built using native https.request using Node Js inside Azure Function and everything works fine. Now I am trying to build Unit Test cases and got struck at mocking Request method.
The callback response has 'on' function which needs to be mocked based on value either 'data' or 'end'.
I get this error TypeError: res.on is not a function
Below is the Code. Any suggestions !
index.js
'use strict';
const https = require('https')
const fs = require('fs')
const path = require('path')
module.exports = function(context, postData) {
//Accessing Certificate and Passing along with Request Options for SSL Handshake
var ca_path = path.join(__dirname, 'my_cert.cer');
https.globalAgent.options.ca = fs.readFileSync(ca_path).toString()
.split(/-----END CERTIFICATE-----\n?/)
// may include an extra empty string at the end
.filter(function(cert) { return cert !== ''; })
// effectively split after delimiter by adding it back
.map(function(cert) { return cert + '-----END CERTIFICATE-----\n'; });
let auth = 'Basic ' + Buffer.from(process.env.username + ':' + process.env.pwd).toString('base64');
let post_option = {
host: process.env.host,
path: process.env.path,
method: 'POST',
port: process.env.port,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
'X-Correlation-ID': JSON.parse(postData).correlationId
}
};
return new Promise(function(resolve, reject) {
var req = https.request(post_option, function(res) {
// accumulate data
var body = [];
res.on('data', function(chunk) { //here is the type error
body.push(chunk);
});
// resolve on end
res.on('end', function() {
context.log("API status: " + res.statusCode);
if (res.statusCode == 200) {
try {
body = JSON.parse(Buffer.concat(body).toString());
context.log("API Success: ");
} catch (err) {
reject(err);
}
resolve(body);
} else if (res.statusCode == 401) {
let errJson = {};
context.log("API authentication error...");
let err = new Error();
errJson["errorCode"] = res.statusCode;
errJson["errorMessage"] = res.statusMessage;
errJson["errorDescription"] = res.statusMessage;
err = errJson;
return reject(err);
} else {
body = JSON.parse(Buffer.concat(body).toString());
context.log("API error...", body);
let err = new Error();
if (body.error != null && body.error != undefined) {
err = body.error;
} else {
let errJson = {};
errJson["errorCode"] = res.statusCode;
errJson["errorMessage"] = res.statusMessage;
errJson["errorDescription"] = res.statusMessage;
err = errJson;
}
return reject(err);
}
});
});
// reject on request error
req.on('error', function(err) {
context.log("API Generic error...", err);
let err = new Error();
let errJson = {};
if (err.message && err.message.indexOf("ENOTFOUND") >= 0)
errJson["errorCode"] = 404;
else
errJson["errorCode"] = 500;
errJson["errorMessage"] = err.message;
errJson["errorDescription"] = err.message;
err = errJson;
reject(err);
});
if (postData) {
req.write(postData);
}
req.end();
});
}
index.test.js
var https = require('https');
jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb('res')({
on: jest.fn()
}),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
/*
jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb('res')({
on: (data, cb) => cb('data')
}),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
*/
/* jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb(jest.fn(() => ({
on: jest.fn()
}))),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
*/
/* jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb({
on: jest.fn()
})
}));
*/
Tried different ways to create mock for 'on' function but not success.
I have an external POST API built using native https.request using Node Js inside Azure Function and everything works fine. Now I am trying to build Unit Test cases and got struck at mocking Request method.
The callback response has 'on' function which needs to be mocked based on value either 'data' or 'end'.
I get this error TypeError: res.on is not a function
Below is the Code. Any suggestions !
index.js
'use strict';
const https = require('https')
const fs = require('fs')
const path = require('path')
module.exports = function(context, postData) {
//Accessing Certificate and Passing along with Request Options for SSL Handshake
var ca_path = path.join(__dirname, 'my_cert.cer');
https.globalAgent.options.ca = fs.readFileSync(ca_path).toString()
.split(/-----END CERTIFICATE-----\n?/)
// may include an extra empty string at the end
.filter(function(cert) { return cert !== ''; })
// effectively split after delimiter by adding it back
.map(function(cert) { return cert + '-----END CERTIFICATE-----\n'; });
let auth = 'Basic ' + Buffer.from(process.env.username + ':' + process.env.pwd).toString('base64');
let post_option = {
host: process.env.host,
path: process.env.path,
method: 'POST',
port: process.env.port,
headers: {
'Content-Type': 'application/json',
'Authorization': auth,
'X-Correlation-ID': JSON.parse(postData).correlationId
}
};
return new Promise(function(resolve, reject) {
var req = https.request(post_option, function(res) {
// accumulate data
var body = [];
res.on('data', function(chunk) { //here is the type error
body.push(chunk);
});
// resolve on end
res.on('end', function() {
context.log("API status: " + res.statusCode);
if (res.statusCode == 200) {
try {
body = JSON.parse(Buffer.concat(body).toString());
context.log("API Success: ");
} catch (err) {
reject(err);
}
resolve(body);
} else if (res.statusCode == 401) {
let errJson = {};
context.log("API authentication error...");
let err = new Error();
errJson["errorCode"] = res.statusCode;
errJson["errorMessage"] = res.statusMessage;
errJson["errorDescription"] = res.statusMessage;
err = errJson;
return reject(err);
} else {
body = JSON.parse(Buffer.concat(body).toString());
context.log("API error...", body);
let err = new Error();
if (body.error != null && body.error != undefined) {
err = body.error;
} else {
let errJson = {};
errJson["errorCode"] = res.statusCode;
errJson["errorMessage"] = res.statusMessage;
errJson["errorDescription"] = res.statusMessage;
err = errJson;
}
return reject(err);
}
});
});
// reject on request error
req.on('error', function(err) {
context.log("API Generic error...", err);
let err = new Error();
let errJson = {};
if (err.message && err.message.indexOf("ENOTFOUND") >= 0)
errJson["errorCode"] = 404;
else
errJson["errorCode"] = 500;
errJson["errorMessage"] = err.message;
errJson["errorDescription"] = err.message;
err = errJson;
reject(err);
});
if (postData) {
req.write(postData);
}
req.end();
});
}
index.test.js
var https = require('https');
jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb('res')({
on: jest.fn()
}),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
/*
jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb('res')({
on: (data, cb) => cb('data')
}),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
*/
/* jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb(jest.fn(() => ({
on: jest.fn()
}))),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
*/
/* jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb({
on: jest.fn()
})
}));
*/
Tried different ways to create mock for 'on' function but not success.
Share Improve this question edited Sep 14, 2021 at 8:25 Sharath Jallu asked Sep 14, 2021 at 7:41 Sharath JalluSharath Jallu 1431 gold badge1 silver badge9 bronze badges1 Answer
Reset to default 6After 3 hours of experiments, finally I was able to mock 'on' function of 'res'.
cb should actually set to a function expecting 2 params
Here is the mock syntax.
let apiResponseBody = `{
"status": "Dummy Request sent to API"
}`;
var https = require('https');
jest.mock('https', () => ({
...jest.requireActual('https'), // import and retain the original functionalities
request: (post_option, cb) => cb({
on: (data, cb) => cb(Buffer.from(apiResponseBody, 'utf8')),
statusCode: 200,
statusMessage: 'API Success'
}),
on: jest.fn(),
write: jest.fn(),
end: jest.fn()
}));
本文标签: javascriptMocking Http Post Request using Jest in NodeJsStack Overflow
版权声明:本文标题:javascript - Mocking Http Post Request using Jest in NodeJs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744030752a2578863.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论