Reputation: 4180
Consider the following function (simplified, shortened for readibility):
function testMe(a)
{
var request = require('request');
return new Promise((resolve, reject)=>{
request.get('someexternalulr?a='+a, (error, response, body) => {
if (error === null)
{
switch(body)
{
case 'one thing':
resolve(true);
break;
case 'something else':
reject(whatever);
break;
// more logic
}
}
else
{
reject(error);
}
});
});
}
It calls an external API, applies some logic to analyze the response, and returns a promise. If I write a jasmine test, API gets called with every test which is (sort of) fine. Yet, I am interested in testing my own logic, not the external API.
What would be the best practice testing such function?
a) Passing dependency on the request module as the 2nd parameter to the function?
b) Moving request to a global variable?
c) Some other trickery?
Upvotes: 0
Views: 782
Reputation: 146520
You need to use a mocking library for the same. sinon is one popular library with jasmine.
const sinon = require('sinon');
const request = require('request');
sinon.stub(request, 'get').yields(null, {}, "<h1>Tarun lalwani</h1>");
const {testMe} = require('./index');
describe("A suite is just a function", function () {
it("should testMe", function (done) {
console.log("we are here")
testMe("tarun").then(data => {
console.log("data", data);
done();
});
})
});
Modified the code you had to export the function for importing
module.exports = {
testMe: function testMe(a) {
var request = require('request');
return new Promise((resolve, reject) => {
request.get('http://vm:8088/?a=' + a, (error, response, body) => {
console.log("response", error,response,body)
if (error === null) {
switch (body) {
case 'some thing else':
reject(whatever);
break;
case 'one thing':
resolve(true)
break;
default:
resolve(body);
break;
}
}
else {
reject(error);
}
});
});
}
}
Upvotes: 1