我在python中寻找类似的东西:http://fgimian.github.io/blog/2014/04/10/using-the-python-mock-library-to-fake-regular-functions-during-tests/
但是对于javascript / node.js来模拟在要测试的代码中使用的类方法或非类方法等,如黑盒子,例如外部依赖。那个node.js当前有什么东西可供使用吗?或者如何模拟python单元测试行为?我目前正在使用mocha& chai for node.js单元测试。以下是预期测试的示例:
var chai = require('chai');
var expect = chai.expect; // we are using the "expect" style of Chai
//SUT module inherits/extends BasicBolt from: https://github.com/apache/storm/blob/master/storm-multilang/javascript/src/main/resources/resources/storm.js
var SUT = require('./../my_code_under_test.js');
var storm = require("./../storm.js");
var fs = require('fs');
var path = require('path');
//...
it('component tests my code, somewhat like a black box', function() {
var myBolt = new SUT.MyCustomBolt();
var cfg = {}, context = {}, done = function() { return; };
myBolt.initialize(cfg,context,done);
var input = fs.readFileSync(path.resolve(__dirname, "input/data.json"),{'encoding':'utf8'});
var tup = new storm.Tuple(1,"default","default",1,["foo",input]);
myBolt.process(tup,done);
//myBolt.process makes HTTP GET call via node.js sync-request module
//myBolt.process then ends by calling a "self.emit()", e.g. BasicBolt.emit()
//for testing purposes, need to mock out request('GET',url) from sync-request, so not need HTTP endpoint to return result
//and need to mock emit such that it simply stores a copy of the emitted data to a (global) variable we can assert against, then reset the variable at end of each test. myBolt.process() itself does not return data to assert against.
expect(theEmittedData).to.equal('some value');
});
//...
我能够使用引用的链接在python中执行此方法。我希望可以在javascript中做同样的事情。或者javascript最佳实践是以不同方式完成的?
仅供参考,我正在编写测试代码来测试代码,而无需在Apache Storm拓扑/基础架构中运行它,只需使用客户端库。由于螺栓相当简单,试图进一步分解myBolt.process()中的代码是不合理的,只是为了避免模拟外部依赖关系,我想测试/使用风暴库& #39; s加上。