【问题标题】:javascript patch an existing external dependency module method with a mocked version in unit testjavascript在单元测试中使用模拟版本修补现有的外部依赖模块方法
【发布时间】:2016-09-22 22:58:17
【问题描述】:

我正在 python 中寻找类似的东西:http://fgimian.github.io/blog/2014/04/10/using-the-python-mock-library-to-fake-regular-functions-during-tests/

但是对于 javascript/node.js 来模拟一个类方法,或非类方法等,使用内部代码进行测试,就像一个黑盒子,e.g.外部依赖。像这样的 node.js 目前有什么可用的吗?或者如何模拟那个 python 单元测试行为?我目前正在使用 mocha & chai 进行 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() 中的代码只是为了避免不得不模拟外部依赖项是没有意义的,我想围绕/使用它与之耦合的风暴库进行测试.

【问题讨论】:

    标签: javascript node.js unit-testing mocking monkeypatching


    【解决方案1】:

    您应该考虑的 2 个库是 sinontestdouble

    【讨论】:

    • 谢谢,这对我来说是一个开始。
    • 我更新了我的问题,您能否提供超出 javascript 模拟库的链接引用的建议?我查看了他们的文档,但还没有弄清楚如何实现我想要的。它不像 python 链接那样清晰(或易于使用)。
    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2015-02-04
    • 2018-06-28
    相关资源
    最近更新 更多