mercredi 14 septembre 2016

Unit test an angular service (not factory) using Jasmine

I've been trying to test an Angular service using Jasmine, and for some reason, no example on here works (mainly simply injecting it inside the angular.mock.inject() method)...

This is the way I got it working, but I am afraid this is not how it should be done...

I basically import the service into the test, setup my module and $provide the service's dependencies, and new the service passing it what would normally be injected...

Anyway, here it is:

import rolesService from './roles.service.js';

describe('Roles', () => {
  let RolesService;
  let PermRoleStore;
  let USER;

  beforeEach(() => {
    angular.mock.module('roles', ($provide) => {
      $provide.constant('USER', {
        roles: ['SOUTIEN_ORGANISME']
      });
      $provide.value('PermRoleStore', {
        defineManyRoles: jasmine.createSpy(),
      });
    });

    angular.mock.inject((_PermRoleStore_, _USER_) => {
      PermRoleStore = _PermRoleStore_;
      USER = _USER_;

      RolesService = new rolesService(PermRoleStore, USER);
    });
  });

  it('Setup should define the roles', () => {
    RolesService.setup();
    expect(PermRoleStore.defineManyRoles).toHaveBeenCalled();
  });

  describe('authorize', () => {
    it('should return true if authorized', () => {
      expect(RolesService.authorize('SOUTIEN_ORGANISME')).toBe(true);
    });

    it('should return false if the user it NOT authorized', () => {
      expect(RolesService.authorize('NOT_AUTHORIZED')).toBe(false);
    });
  });
});

Aucun commentaire:

Enregistrer un commentaire