0

I am writing a class in JavaScript that sends HTTP requests for a specific URL. I'm trying to test that class with Mocha but for some reason, the method fetchUrl() returns undefined. I can't seem to figure out why. I literally started writing in JavaScript a day ago, therefore I am still trying to learn and adjust to it.

 fetchUrl () {
    var request = require('request')
    var res
    request(this.url, function (error, response, body) {
      console.log('error:', error) // Print the error if one occurred
      if (response.statusCode !== 200) {
        console.log('received status code other than 200 OK')
        this.error = true
      }
      res = response
      console.log('statusCode:', response && response.statusCode) // Print the response status code if a response was received
      // console.log('body:', body) // Print the HTML for the requested url.
      this.html = body
    })
    return res
  }

describe('Test Http request to google.com', function () {
  it('should return 200', function (done) {
    assert.equal(httpCon.fetchUrl().statusCode, 200)
    done()
  })
})
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
  • `fetchURL` is returning undefined because `res` is not defined before return statement and you are expecting definition inside your async code. – Rikin Jul 12 '18 at 13:32
  • Or possibly better [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Liam Jul 12 '18 at 13:40

2 Answers2

0

You should use Nock libray to mocking HTTP request.

const axios = require('axios');
module.exports = {
   getUser(username) {
     return axios
        .get(`https://api.github.com/users/${username}`)
        .then(res => res.data)
        .catch(error => console.log(error));
    }
};

And here test case:

describe('Get User tests', () => {
    beforeEach(() => {
       nock('https://api.github.com')
         .get('/users/octocat')
         .reply(200, response);
    });
});

For more details, you can look at this: mocking-http also look into this answer of SO. source

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
-3

I think you should only return res inside the callback, otherwise it will return undefined since the program keeps running... https://developer.mozilla.org/en-US/docs/Glossary/Callback_function You may want to take a look on callback funcionality