3

I am working on a framework with modules which are loaded asynchronously using promises. These modules contain methods (which, for this question, can be assumed to be synchronous) for which I would like to create tests for.

Currently, my code resembles the following:

describe("StringHelper", function() {
    describe("convertToCamelCase()", function() {
        it("should convert snake-cased strings to camel-case", function(done) {
            Am.Module.load("Util").then(function() {
                var StringHelper = Am.Module.get("Util").StringHelper;
                //Test here
                done();
            });
        });
    });

    describe("convertToSnakeCase()", function() {
        it("should convert camel-cased strings to snake case.", function(done) {
            Am.Module.load("Util").then(function() {
                var StringHelper = Am.Module.get("Util").StringHelper;
                //Another test here
                done();
            });
        });
    });
});

Given that Am.Module.load() is essentially a call to RequireJS wrapped in such a way to return a promise, and hence, should be only loaded once at the beginning, how can I rewrite the above?

I'm essentially hoping to have something like this:

Am.Module.load("Util").then(function() {
    var StringHelper = Am.Module.get("Util").StringHelper;

    describe("StringHelper", function() {
        describe("convertToCamelCase()", function() {
            it("should convert snake-cased strings to camel-case", function(done) {
                //Test here
                done();
            });
        });

        describe("convertToSnakeCase()", function() {
            it("should convert camel-cased strings to snake case.", function(done) {
                //Another test here
                done();
            });
        });
    });
});

Unfortunately, the above does not work - the tests are simply not being executed. The reporter doesn't even display the part for describe("StringHelper"). Interestingly, after playing around, this only occurs if all the tests are written in this (the second code snippet) manner. As long as there is at least one test written in the first format, the tests show up properly.

Alvin Teh
  • 615
  • 9
  • 13

1 Answers1

1

You can use Mocha's before() hook to load the Util module asynchronously.

describe("StringHelper", function() {
  var StringHandler;

  before(function(done) {
    Am.Module.load("Util").then(function() {
      StringHelper = Am.Module.get("Util").StringHelper;
      done();
    });
  });
  describe("convertToCamelCase()", function() {
    it("should convert snake-cased strings to camel-case", function() {
      //Test here
    });
  });

  describe("convertToSnakeCase()", function() {
    it("should convert camel-cased strings to snake case.", function() {
      //Another test here
    });
  });
});
JME
  • 3,452
  • 12
  • 22