0

I'm writing tests for a JS application using Jasmine and testdouble.js as a mocking library. I am using AMD format to organize code in modules, and RequreJS as a module loader. I was wondering how to use testdouble.js to replace dependency for the module being tested that is in AMD format and it is loading via RequireJS. The documentation is unclear about this or I am missing something, so if someone could point me in the right direction.

I'll post the example bellow that illustrates my setup and the problem that I am facing.

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());
    });
  });
});

1 Answer 1

1

testdouble.js does not have any explicit support for AMD modules. The only module-related tricks it offers are Node.js specific and built on top of Node's CJS module loader.

What you would need to do in this case is require from the test a reference to engine and replace the run property, which it seems like you've done (your example is incomplete).

If you do this, don't forget to run td.reset() in an afterEach to restore the original properties to anything you replace!

Not the answer you're looking for? Browse other questions tagged or ask your own question.