1

My http call returns a function, so my comparison always fails as [Function] isn't equal to my value.

How can I get my assert to use the true/false flag inside it?

# test/helloWorld.js
const other_functions = require('../other_file');
describe('function from other file,visits URL', function() {
  it('should visit example.com', function() {
    result = other_functions.oo
    console.log(result);
    assert.equal(result, true);
  }); 
});
# other_file.js
const request = require('request')
var http_call = request('http://example.com', function (error, response, body) {
  console.error('error:', error);
  console.log('statusCode:', response && response.statusCode);
  console.log('body:', body);
  if(body.match(/Example Domain/)) {
    return true
  }
  else {
    return false
  }
});
exports.oo = () => {
  return http_call
}
npm test
...
AssertionError [ERR_ASSERTION]: [Function] == true       
...
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • but what do you have inside the returned function? An object, a promise ? Why dont you set the Boolean flag to the contents of the function itself? – ZombieChowder Jan 06 '20 at 20:34
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Jan 11 '20 at 22:57

1 Answers1

2

Callbacks don't return a value so you need to either pass the callback to get the value or change it to use promise style. Something like this

const request = require('request')
function http_call() {
  return new Promise((resolve, reject) => {
    request('http://example.com', function (error, response, body) {
      console.error('error:', error);
      console.log('statusCode:', response && response.statusCode);
      console.log('body:', body);
      if(body.match(/Example Domain/)) {
        resolve(true)
      }
      else {
        resolve(false);
      }
    });
  });
}

module.exports = http_call;

and then in your test you can do

const http_call = require('../other_file');
describe('function from other file,visits URL', function() {
  it('should visit example.com', async function() {
    const result = await http_call();
    console.log(result);
    assert.equal(result, true);
  }); 
});

Hope this helps

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35