Flushing anonymous module call in Jasmine with requireJs

Setting up the current test block:

  • Jasmine 2.1
  • RequireJs 2.1.15
  • Chutzpah 3.2.6

In our codebase, we have a number of modules that are loaded via requireJs for abstract functionality. For example, communication that abstracts requests to the server. However, these modules return an anonymous function:

define(['jquery'], function ($) {

    return function (method, link, payload) {
        // code removed as not required for question
        return $.ajax({
            type: method,
            url: link,
            data: payload
        });
    };
})

      

It is then imported using requireJs / AMD load by other modules and used like this:

var promise = communicator("GET", "/url/to/my/webapi", {});

      

I currently have a mock module that is imported for unit tests, bypassing the $ .ajax call and returning a promise, but I really want to check in my unit tests that it was called or not and the correct values ​​were passed, etc. etc. I've tried looking at spy, but since it doesn't expose the named function in the module, I can't seem to use that method as far as I can tell.

How can I set expectations / mock AMD's anonymous return function?

EDIT

Usage example for clarity:

define(['communicator'], function (communicator) {

        var vm = function (id) {
            var self = this;

            self.Id = id

            self.submitForm = function () {
                var data = { };

                var promise = communicator("PUT", "/url/to/web/api", data);

                promise.done(function (message) {
                });

                promise.fail(function (error) {
                });
            };
        };

        return {
            initialise: function (params) {
                var viewModel = new vm(params.Id);
                return viewModel;
            }
        };
    });

      

I want to be able to test the submitForm function (simplified for request purposes) and want to mock the communicator dependency without defining a hardcoded plug-in in the require.js setup test project.

+3


source to share


2 answers


I'm not sure exactly what you need to check, but you could spyOn $.ajax

and create your own promise ...



window.spyOn($, "ajax").and.callFake(function() {
  var d = $.Deferred();
  d.resolve(true);
  return d.promise();
});

expect($.ajax).toHaveBeenCalled();
// other expects...

      

+2


source


In the end, I went with modifying the module to have special methods to follow. I have other modules that share the same template, although this will continue in my quest.



0


source







All Articles