gpt4 book ai didi

javascript - Rewire - 同一模块中的模拟依赖

转载 作者:行者123 更新时间:2023-11-29 23:57:42 26 4
gpt4 key购买 nike

假设我有一个包含两个函数的模块,其中一个函数依赖于另一个函数:

// 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');
});
});

最佳答案

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

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

这样做解决了我的问题。

关于javascript - Rewire - 同一模块中的模拟依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com