Michael Durrant
Michael Durrant

Reputation: 96614

How to get mocha to use http response?

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       
...

Upvotes: 1

Views: 535

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

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

Upvotes: 2

Related Questions