我正在尝试模拟 request-promise在使用 Sinon 的测试中.据我所知,Sinon 模拟对象的方法,而请求 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,但我认为它们都遇到了类似的问题。
最佳答案
下面的示例应该可以为您解决问题。通过使用 proxyquire,您可以包装 request-promise
并避免 stub .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);
});
});
关于javascript - 使用 Sinon 模拟 require() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063933/