将 AMD 模块格式的依赖项替换为 testdouble.js

Replacing dependencies in AMD module format with testdouble.js

我正在使用 Jasmine 和 testdouble.js 作为模拟库为 JS 应用程序编写测试。我使用 AMD 格式在模块中组织代码,并使用 RequreJS 作为模块加载器。我想知道如何使用 testdouble.js 替换正在测试的 AMD 格式的模块的依赖项,它是通过 RequireJS 加载的。文档对此不清楚,或者我遗漏了一些东西,所以如果有人能指出我正确的方向。

我将 post 下面的示例说明我的设置和我面临的问题。

car.js

define("car", ["engine"], function(engine) {
  function drive = {
    engine.run();
  }

  return {
    drive: drive
  }
});

engine.js

define("engine", function() {
  function run() {
    console.log("Engine running!");
  }

  return {
    run: run
  }
});

car.spec.js

define(["car"], function(car) {
  describe("Car", function() {
    it("should run the motor when driving", function() {
      // I am not sure how to mock the engine's object run method
      // and where to place that logic, in beforeEach or...
      td.replace(engine, "run");
      car.drive();
      // How to verify that when car.run() has executed, it calls this mocked method
      td.verify(engine.run());
    });
  });
});

testdouble.js 没有任何对 AMD 模块的明确支持。它提供的唯一与模块相关的技巧是 Node.js 特定的,并且构建在 Node 的 CJS 模块加载器之上。

在这种情况下,您需要做的是从测试中获取对 engine 的引用并替换 run 属性,看起来您已经完成了(你的例子不完整)。

如果您这样做,请不要忘记在 afterEach 中 运行 td.reset() 将原始属性恢复为您替换的任何内容!