NodeJS 中用于单元测试的模块导出回调

Module export callback in NodeJS for Unit Test

在我的项目中使用axios建立服务器连接的代码如下:

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

我正在使用 Jest 作为测试框架,并且我成功模拟了 axios,但是我对这个 then-Function 有问题:

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

但是,当 运行 测试时,我收到以下错误消息:

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

我必须以某种方式找到一种方法来说明 then 存在并且是一个函数。我必须在 module.exports 中执行此操作。关于如何做到这一点有什么想法吗?

您似乎期待 get 函数 return 一个 Promise。这就是 then 函数的含义。为此,您可以将 get 模型更改为如下所示:

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

或者,如果您知道它总是会成功,您可以使用 Promise.resolve:

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

Promises 的伟大之处在于它们简化了异步过程。对于您的模型,这就是您所需要的,但您可以使用相同的过程来处理异步值。

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);
    });
  }
};

那么当你使用这个模块时,就很简单了:

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