如何存根 require() / Expect 调用模块的“root”函数?

2023-12-24

考虑以下茉莉花规格:

describe("something.act()", function() {
  it("calls some function of my module", function() {
    var mod = require('my_module');
    spyOn(mod, "someFunction");
    something.act();
    expect(mod.someFunction).toHaveBeenCalled();
  });
});

这工作得很好。像这样的东西使它变成绿色:

something.act = function() { require('my_module').someFunction(); };

现在看一下这个:

describe("something.act()", function() {
  it("calls the 'root' function of my module", function() {
    var mod = require('my_module');
    spyOn(mod); // jasmine needs a property name
                // pointing to a function as param #2
                // therefore, this call is not correct.
    something.act();
    expect(mod).toHaveBeenCalled(); // mod should be a spy
  });
});

这是我想用这个规范测试的代码:

something.act = function() { require('my_module')(); };

在过去的几个月里,这让我多次陷入困境。一种理论上的解决方案是替换 require() 并返回使用 createSpy() 创建的间谍。但是 require() 是一个不可阻挡的野兽:它是每个源文件/模块中函数的不同“副本”。在规范中存根它不会替换“testee”源文件中真正的 require() 函数。

另一种方法是在加载路径中添加一些假模块,但对我来说它看起来太复杂了。

任何想法?


rewire https://github.com/jhnns/rewire太棒了

var rewire = require('rewire');

describe("something.act()", function() {
  it("calls the 'root' function of my module", function() {
    var mod = rewire('my_module');
    var mockRootFunction = jasmine.createSpy('mockRootFunction');
    var requireSpy = {
      mockRequire: function() {
        return mockRootFunction;
      }
    };
    spyOn(requireSpy, 'mockRequire').andCallThrough();

    origRequire = mod.__get__('require');
    mod.__set__('require', requireSpy.mockRequire);

    something.act();
    expect(requireSpy.mockRequire).toHaveBeenCalledWith('my_module');
    expect(mockRootFunction).toHaveBeenCalled();

    mod.__set__('require', origRequire);
  });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何存根 require() / Expect 调用模块的“root”函数? 的相关文章

随机推荐