ReactiveRaven
ReactiveRaven

Reputation: 7541

Get angular constants in Karma

Given the app startup:

angular.module("starter", [ "ionic" ])
    .constant("DEBUG", true)
    .run(function() {
        /* ... */
    });

how would I test the value of DEBUG?

When trying with:

describe("app", function() {

    beforeEach(function() {
        module("starter");
    });

    describe("constants", function() {
        describe("DEBUG", inject(function(DEBUG) {
            it("should be a boolean", function() {
                expect(typeof DEBUG).toBe("boolean");
            });
        }));
    });
});

I just get

TypeError: 'null' is not an object (evaluating 'currentSpec.$modules')
    at workFn (/%%%/www/lib/angular-mocks/angular-mocks.js:2230)
    at /%%%/www/js/app_test.js:14
    at /%%%/www/js/app_test.js:15
    at /%%%/www/js/app_test.js:16

Upvotes: 4

Views: 5210

Answers (2)

Grey Perez
Grey Perez

Reputation: 20468

Simple way to inject your existing constants into your karma tests.

// Assuming your constant already exists
angular.module('app').constant('STACK', 'overflow')...

// Your Karma Test Suite
describe('app', function() {
    var STACK;

    beforeEach(module('APP'));

    beforeEach(inject(function ($injector) {
        STACK = $injector.get('STACK');
    }));

    // Tests...
});

Upvotes: 3

ReactiveRaven
ReactiveRaven

Reputation: 7541

Make sure it is being instantiated in the right place. In this case, the beforeEach was not being run to load the module, because DEBUG was being inject()ed in the describe block, not the it block. The following works properly:

describe("app", function() {

    var DEBUG;

    beforeEach(function() {
        module("starter");
    });

    describe("constants", function() {
        describe("DEBUG", function() {
            it("should be a boolean", inject(function(DEBUG) {
                expect(typeof DEBUG).toBe("boolean");
            }));
        });
    });
});

Upvotes: 5

Related Questions