1

I'm having some issues with a Jasmine unit-test seeing a global variable as undefined. I'm using Squire to mock some classes with the dependencies injected via RequireJS. Here is a trimmed down example of my unit test:

My 'service' class (service.js)

define(['durandal/system', 'cache'],
    function (system, cache) {
        var dataservice = {

            retrieveData: function () {
                return cache.getCachedData();
            }
        };

        return dataservice;
});

My fixture to mock the 'cache' dependency.

define(['Squire'], function (Squire) {
    var injector = new Squire();

    return {
        initialize: function () {
            injector.clean();

             injector.mock('cache', {
                getCachedData: function () {
                    return { item: "one" };
                }
            });

            return injector;
        }
    };
});

And my spec:

define(['dataservice_fixture', 'durandal/system'],
    function (testFixture, system) {
        var container = testFixture.initialize();
        var dataserviceModule;

        container.require(['service'], function (preparedDataservice) {
            dataserviceModule = preparedDataservice;
        });

        describe('The data service ', function () {
            it('should exist.', function () {
                expect(dataserviceModule).toBeDefined();
            });
        });
    });

In my 'should exist' test, dataserviceModule is undefined. I would expect it to be though when my fixture (container above) pulls it in. Now, if I pull in 'service' at the top of my spec in the define(), and set dataserviceModule there, the test sees it as defined.

Why exactly is my container.require either not setting the variable one scope higher, or being lost between that and the test running? I read this this question around hoisting, but I'm not re-declaring the same variable name within my container.require.

1 Answer 1

1

Looks like this is actually a race condition in that the tests are being ran before my module can be loaded. I added in waitsFor and a latch that is true after my module is loaded to resolve this.

For anyone who runs across, check out http://www.htmlgoodies.com/beyond/javascript/test-asynchronous-methods-using-the-jasmine-runs-and-waitfor-methods.html

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