以下示例應該爲您解決問題。通過使用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);
});
});
來源
2017-09-14 22:17:47
PRS
更直接的解決方案是末梢rp.get,rp.post等N.B.這需要更改您自己的模塊以使用rp.get({..})/ rp.post({..})來代替rp({..})。可以說,它也更容易閱讀。 – Typhlosaurus