Cannot call beforeEach 'inject' on angularJS (FUSE Admin) unit testing using karma

224 Views Asked by At

I used FUSE Admin app on my project - http://fuse-angular-material.withinpixels.com/apps/dashboards/project.

I already checked other samples and even run this code on a different project and works just fine. IT's just that I cannot inject the service, controller etc. on 'beforeEach inject', thus I cannot cont. my test.

I don't know what's wrong or did I miss something (dependencies? not sure) while running this on FUSE. Do you have any idea?

Here's my code.

SERVICE (the service returns a list of array)

(function () {
    'use strict';

    angular
        .module('app.admin.users', [])
        .config(config)
        .service('adminUserService', service);

    function service(msApi) {
        return {
            adminUserList: function () {
                return msApi.resolve('admin.users.list@query');
            }
        };
    }

    function config(msApiProvider) {
       // calling the API (used dummy data)
        msApiProvider.register('admin.users.list',['app/data/admin/users/users.json']);
    }

})();

UNIT TEST

var oDataService;
var adminUserService;

describe('unit test ----------------------------', function () {
    beforeEach(module('app.admin.users'));

    beforeEach(function () {
        inject(function ($injector) {
            adminUserService = $injector.get('adminUserService');
            oDataService = adminUserService.adminUserList();
        });
    });

    it("is registered with the module.", function () {
        expect(oDataService).not.toBe(null);
    });
});
1

There are 1 best solutions below

2
On

First, you should move 'it' block outside of beforeEach block. Then to get the service from the module, there are two approaches.

  1. Using injector (not common):

    Here you need to manually create a injector from the module.

    it('test my service', function(){
        var $injector = angular.module(['app.admin.users'])
        var service = injector.get('adminUserService')
        expect(service.adminUserList()).not.toBe(null);
    });
    
  2. Using inject (more common)

    it('test my service', inject(function(adminUserService){
        expect(adminUserService.adminUserList()).not.toBe(null);
    }));
    

As you can see 2nd approach is lot easier.

Refer this also: Injecting Services