Mock Dojo Module: Any Working Examples?

1705
2
09-29-2016 04:42 PM
ZianChoy
Occasional Contributor

I can't find any example of someone mocking a Dojo module successfully.

I found https://gis.utah.gov/mock-your-dojo-amd-modules-with-stubmodule-js/ but when I try to run StubModule, I get an error at line 27 of stub-module.js because "modules" isn't a member of the require variable.

I also looked into Sinon.js but they don't say anything about mocking AMD modules (http://sinonjs.org/docs/#mocks).

Does anyone know of any working examples of someone mocking a Dojo AMD module?

0 Kudos
2 Replies
ReneRubalcava
Frequent Contributor

I supposed it depends on exactly what you want to mock.

For example, you can use Sinon to stub out methods of a module, just remember to reset them so you don't taint other tests.

Something like this generator-arcgis-js-app/helpers-mapgenerator.js at master · odoe/generator-arcgis-js-app · GitHub 

  registerSuite({
    name: 'helpers: mapgenerator',
    setup: function() {
      // set up test here
    },
    beforeEach: function() {
      // run before
      sinon.stub(arcgisUtils, 'createMap').returns({
        then: function(){}
      });
    },
    afterEach: function() {
      // run after
      arcgisUtils.createMap.restore();
    },
    teardown: function() {
      // destroy widget
    },
    'helper attempts to create map': function() {
      var params = { id: 'test', webmapid: '1234' };
      helper.fromWebMapAsJSON(params);
      expect(arcgisUtils.createMap).to.have.been.calledOnce;
    },
  });
0 Kudos
ZianChoy
Occasional Contributor

Based on your example, does that mean I can write something like:

require([
  'firstwatch/HelloWorld',

  'dojo/promise/Promise',
  'dojo/promise/all',
  'firstwatch/tests/stub-module'
 ],

 function (
  HelloWorld,
  Promise,
  all,
  stubModule) {
 describe("A suite", function () {

beforeEach: function() {
      // run before
      sinon.stub(dom, 'methodInDOM').returns({
        then: function(){}
      });
    },
  it("contains spec with an expectation", function () {
   expect(HelloWorld.deadOrAlive()).toBe("alive");
  
  });
 });
});

to test the following module ("HelloWorld.js") without making the browser actually go out and make an instance of dojo/dom?

define(["dojo/dom"], function(dom) {
    return {
        saySomething: function() {
            alert("Hello world");

dom.doSomethingPointless();
        },
  deadOrAlive: function(){
   return "alive";
  }
    };
});

0 Kudos