今天春天 今天春天 - 6 months ago 50
Node.js Question

Module export callback in NodeJS for Unit Test

I have the following piece of code to establish a server connection using axios in my project:

axios.get('/someurl')
.then(function (response) {
console.log(response);
}.bind(this))
.catch(function (response) {
console.log(response);
});


I am using Jest as a testing framework and I successfully mocked axios, but I have a problem with this then-Function:

module.exports = {
get: function(a)
console.log(a);
console.log(b);
return "abc";
}
}


However, when running the tests I get the following error message:


TypeError: _axios2.default.get(...).then is not a function


I must somehow find a way to tell that then exists and is a function. I must do this in the module.exports. Any ideas on how to do this?

Answer

You seem to be expecting the get function to return a Promise. That's what the then function implies. To do that, you can change your get mockup to something like this:

module.exports = {
  get: function(a) {
    return new Promise(function(resolve, reject) {
      console.log(a);
      console.log(b);
      resolve('abc');
    });
  }
};

Or, if you know that it will always be successful, you can simplify it using Promise.resolve:

module.exports = {
  get: function(a) {
    console.log(a);
    console.log(b);
    return Promise.resolve('abc');
  }
};

The great thing about Promises is they simplify asynchronous processes. For your mockup, this is all you need but you can use this same process for working with an asynchronous value.

module.exports = {
  get: function(a) {
    return new Promise(function(resolve, reject) {
      // Wait some period of time
      setTimeout(function() {
         // 'abc' + a is passed to the `then` function
         resolve('abc' + a);
      }, 1000);
    });
  }
};

Then when you're using this module, it's as simple as:

var axios = require('./my-mockup.js');
axios.get('def')
.then(function(response) {
  console.log(response); // 'abcdef'
});