使用Sinon模拟require()'d函数
Mocking a require()'d function using Sinon
我试图在使用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() {});
我也研究了mockrequire和proxyquire,但我认为它们都遇到了类似的问题。
下面的示例应该会让您明白。通过使用代理,您可以包装request-promise
,避免存根.post
, .get
, .call
等。我觉得干净多了。
myModule.js
:
'use strict';
const rp = require('request-promise');
class MyModule {
/**
* Sends a post request to localhost:8080 to create a character.
*/
static createCharacter(data = {}) {
const options = {
method: 'POST',
uri: 'http://localhost:8080/create-character',
headers: {'content-type': 'application/json'},
body: data,
};
return rp(options);
}
}
module.exports = MyModule;
myModule.spec.js
:
'use strict';
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const requestPromiseStub = sinon.stub();
const MyModule = proxyquire('./myModule', {'request-promise': requestPromiseStub});
describe('MyModule', () => {
it('#createCharacter', (done) => {
// Set the mocked response we want request-promise to respond with
const responseMock = {id: 2000, firstName: 'Mickey', lastName: 'Mouse'};
requestPromiseStub.resolves(responseMock);
MyModule.createCharacter({firstName: 'Mickey', lastName: 'Mouse'})
.then((response) => {
// add your expects / asserts here. obviously this doesn't really
// prove anything since this is the mocked response.
expect(response).to.have.property('firstName', 'Mickey');
expect(response).to.have.property('lastName', 'Mouse');
expect(response).to.have.property('id').and.is.a('number');
done();
})
.catch(done);
});
});
我找到了一个(某种)解决方案。
基本上,你搭载了call
(apply
也可以):
// 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' });
});
});
它完成了工作,尽管我不喜欢到处都要做rp.call
,所以我仍然对更好的解决方案抱有希望。
相关文章:
- Stubbing Backbone类构造函数与Jasmin和Sinon
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 使用sinon.js创建一个“;“间谍对象”;使用基于真实构造函数/原型的间谍方法
- sinon 存根嵌套在描述/请求函数中
- Sinon-带有回调的存根函数-导致测试方法超时
- 在sinon中存根嵌套函数调用
- 如何使用 sinon.js 来模拟/监视 javascript 函数中提到的对象
- 使用 Sinon.js 测试一个函数是否调用 ES6 模块中的另一个函数
- sinon.js监视$.dataTables函数
- 如何使用sinon.js实现mock/stub回调函数
- 如何使用Chai/Sinon重构jasmine.any()函数
- 如何监视jQuery's附加函数Sinon
- 如何使用Sinon创建阻止实际函数执行的测试替身
- 什么'这个异步JavaScript函数的单元测试是错误的(通过Mocha/Sinon)
- 如何用Sinon.js监视与被测函数在同一js文件中的函数
- 我如何使用sinon存根函数为neo4j Thingdom模块
- 用sinon监视Date构造函数
- 当断言函数调用时,chaispy不能识别Sinon存根函数
- 使用Sinon模拟require()'d函数
- 监视函数sinon返回的函数