【问题标题】:Rewire - Mock Dependency In Same ModuleRewire - 同一模块中的模拟依赖关系
【发布时间】:2016-12-22 19:40:20
【问题描述】:

假设我有一个具有两个功能的模块,其中一个依赖于另一个:

// example.js
function A() {
    return "hello";
}

function B() {
    return A();
}

module.exports.B = B;

我可以使用 rewire 来模拟 B() 中对 A() 的调用吗?

// example.test.js
var assert = require('chai').assert,
    rewire = require('rewire'),
    example = rewire('./example.js');

example.__set__({
    A: function( return 'goodbye';),
});

describe('test B in example.js', function() {
    it('should return "goodbye"', function() {
        assert.strictEqual(example.B(), 'goodbye');
    });
});

【问题讨论】:

    标签: javascript unit-testing mocking


    【解决方案1】:

    是的,这确实有效。我不确定究竟是什么解决了这个问题。以前我将依赖函数作为函数原型的一部分导出(例如function.prototype.dependentFunction = function() { };),不知何故这与重新布线有关。我通过首先声明/定义它然后将其附加到模型来重新定义我的函数:

    function dependentFunction() { ... }
    exportedObject.prototype.dependentFunction = dependentFunction();
    

    这样做解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 2020-01-11
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 2018-02-19
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多