2

I want to use jasmine's beforeAll instead of beforeEach but angular.mock.module and angular.mock.inject functions are not working in beforeAll whereas they're working in beforeEach.

Here is my test. the same code is working in beforeEach approach.

describe("This is a test", function () {
    beforeAll(module("app"));

    var vm;
    beforeAll(function() {
        angular.mock.module(function ($provide) {
            $provide.factory("dataService", ["$q", function ($q) {
                return {
                    getSomeDataById: function () { return $q.resolve({ }); }
                };
            }]);
        });

        angular.mock.inject(function (_$controller_,dataService) {
            vm = _$controller_("TestController",
            {
                dataService: dataService
            });
        });
    });
});

1 Answer 1

2

I was facing a similar problem and using the module.sharedInjector() call resolved it for me:

describe("This is a test", function () {

    // Call SharedInjector before any call that might invoke the injector
    angular.mock.module.sharedInjector();

    beforeAll(module("app"));

    var vm;
    beforeAll(function() {
        angular.mock.module(function ($provide) {
            $provide.factory("dataService", ["$q", function ($q) {
                return {
                   getSomeDataById: function () { return $q.resolve({ }); }
               };
            }]);
        });

        angular.mock.inject(function (_$controller_,dataService) {
            vm = _$controller_("TestController",
            {
                dataService: dataService
            });
        });
    });
});

A quick snippet from the linked docs page to explain why that works (emphasis mine):

[angular.mock.module.sharedInjector] ensures a single injector will be used for all tests in a given describe context. This contrasts with the default behaviour where a new injector is created per test case.

Use sharedInjector when you want to take advantage of Jasmine's beforeAll(), or mocha's before() methods. Call module.sharedInjector() before you setup any other hooks that will create (i.e call module()) or use (i.e call inject()) the injector.

Sign up to request clarification or add additional context in comments.

1 Comment

Added the context from the docs link you provided. Hope that's okay! Makes it an even stronger answer imo. Couldn't google this up to save my life; thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.