我有以下代码在我的项目中使用 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
函数返回 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');
}
};
Promise 的伟大之处在于它们简化了异步流程。对于您的模型,这就是您所需要的,但您可以使用相同的过程来处理异步值。
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'
});
关于javascript - NodeJS 中的模块导出回调用于单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37334889/