我在我的项目中使用节点rest客户端,我已经到了想要开始使用节点-rest-客户机的类的单元测试的地步了。有关于如何在我的测试中模拟客户端的模拟的例子吗?我在单元测试中使用西农。
发布于 2017-05-09 15:57:48
步骤1:在您正在测试的js代码中,导出节点-rest-客户机实例,以便它可以用于您的测试代码。例如,在myApp.js中,我说:
var Client = require('node-rest-client').Client;
var restClient = new Client();
exports.restClient = restClient; //instance now available outside this module
restClient.get(someUrl, ...); //actual node rest client call
步骤2:在测试代码中,创建一个返回假函数的包装函数,并使用sinon将其模拟到目标代码中。这允许您在测试设置期间注入返回数据和响应代码。
var nodeRestGet = function (data, statusCode) {
return function (url, cb) {
cb(data, { statusCode: statusCode || 200 });
}
};
sinon.stub(myApp.restClient, 'get').callsFake(nodeRestGet("", 200));
第三步:编写测试代码。请注意,如果正在运行多个测试,则可能希望还原该方法(移除模拟):
myApp.doThings(); // TEST
myApp.restClient.get.restore(); // removes the mock
https://stackoverflow.com/questions/43756402
复制相似问题