我正在使用rewire
来测试我的节点控制器。我有以下端点使用request
来获取一些数据。
exports.myGetEndpoint = function(req, res) {
return request.get({
url: 'http://baseURL/api/myGetEndpoint',
headers: {
authorization: { //etc }
},
json: true
})
.then(function(data) {
res.status(200).json(data.objects);
});
};
我想测试一下,当我从控制器调用get
方法时,request
会被正确的参数调用,但我对如何使用'存根'或者是间谍'根据要求。
var Promise = require('bluebird');
var rewire = require('rewire');
var controller = rewire('../../controllers/myGetEndpoint.js');
var request = {
get: sinon.stub()
};
// Use rewire to mock dependencies
controller.__set__({
request: request
});
describe('myGetEndpoint', function() {
var json;
var req;
var res;
beforeEach(function(done) {
json = sinon.spy();
req = { headers: {} };
res = {
status: sinon.stub().returns({
json: json
})
};
controller.myGetEndpoint(req, res).then(function() {
done();
});
});
it('should call the correct request arguments', function() {
// lost
});
});
答案 0 :(得分:0)
我要修改一下你的源代码,只使用一个回调而不是一个promise。我需要研究如何使用sinon存储一个promise,但是你可以通过一个简单的回调来了解如何测试它:
exports.myGetEndpoint = function(req, res) {
return request.get({
url: 'http://baseURL/api/myGetEndpoint',
headers: {
authorization: { //etc }
},
json: true
}, function (error, response, body) {
res.status(200).json(response.objects);
});
};
您不应该在beforeEach中调用控制器,但必须在测试用例中调用它。 beforeEach通常用于在测试用例之前进行初始化:
var expect = require('chai').expect;
var Promise = require('bluebird');
var rewire = require('rewire');
var controller = rewire('../../controllers/myGetEndpoint.js');
var request = {
get: sinon.stub()
};
// Use rewire to mock dependencies
controller.__set__({
request: request
});
describe('myGetEndpoint', function() {
var status;
var json;
var req;
var res;
beforeEach(function(done) {
json = sinon.spy();
status = sinon.stub();
req = { headers: {} };
res = {
status: status.returns({
json: json
})
};
});
it('should call the correct response arguments', function(done) {
var response = {objects: ['objects', 'objects']}
request.get.yields(null, response);
controller.myGetEndpoint(req, res);
expect(status.calledWith(200)).to.equal(true);
expect(json.calledWith(response.objects)).to.equal(true);
});
});
P.S。:我实际上并没有尝试运行它,所以也许有一些错别字。