使用Sinon模拟require()函数
I'm trying to mock request-promise in a test using Sinon. As far as I can tell, Sinon mocks methods of objects, and yet request-promise simply returns a function. Is there any way to mock a single required function?
我正试图在使用Sinon的测试中模拟请求 - 承诺。据我所知,Sinon嘲笑对象的方法,但是request-promise只返回一个函数。有没有办法模拟一个必需的功能?
var rp = require('request-promise');
var User = require('../../models/user');
// this works
sinon.stub(User, 'message', function() {});
// This is what I'd like to do to request-promise
sinon.stub(rp, function() {});
I've also looked into mockrequire and proxyquire but I think they both run into similar issues.
我也看过mockrequire和proxyquire,但我认为他们都遇到了类似的问题。
2 个解决方案
#1
1
I found a (sort of) solution here.
我在这里找到了一种(某种)解决方案。
Basically, you piggyback off of call
(apply
would also work):
基本上,你背负电话(申请也可以):
// models/user.js
var rp = require('request-promise');
var User = {
save: function(data) {
return rp.call(rp, {
url: ...,
data: data
});
}
}
module.exports = User;
// test/user.js
var rp = require('request-promise');
var User = require('../../models/user');
describe('User', function() {
it('should check that save passes data through', function() {
sinon.stub(rp, 'call', function(data) {
// check data here
});
User.save({ foo: 'bar' });
});
});
It gets the job done, although I'm not a fan of having to do rp.call
everywhere, so I'm still holding out hope for a better solution.
它完成了工作,虽然我不喜欢在任何地方都做rp.call,所以我仍然希望有更好的解决方案。
更多相关文章
- 【问题解决方案】ImportError: No module named 'pygal'
- Python 黏包及黏包解决方案
- 无法安装ndg-httpsclient或者我的解决方案错误
- Linux无法连接网络解决方案
- Media-S 简介(一个开源的DRM解决方案)
- AppScan安全问题解决方案
- PLSQL乱码解决方案
- 数据库不支持中文解决方案(mysql)
- Mysql替代解决方案Cassandra