How can I access my service from module setup in Angular Jasmine Test?

310 views Asked by At

I have the following in a jasmine test for angular...

  beforeEach(module('app'));
  beforeEach(module('app.services'));

  beforeEach(module(function ($provide, Config) {

    reservationCallerJquery = {
      reserveBooking: function (reservationRequestDto, reserveBookingSuccess) {
        doJqueryPost(reservationRequestDto.item,
          "I need a value from my config class",
          reserveBookingSuccess);
      }

    $provide.value("ReservationCaller", reservationCallerJquery);


  }));

But I get the error:

Error: [$injector:modulerr] Failed to instantiate module function ($provide,Config) due to: Error: [$injector:unpr] Unknown provider: Config

So how do I set that string of my stub to something from config? (The Config lives in the 'app.services')...I think I need to get it from there but how?

1

There are 1 answers

0
Boris Charpentier On

You'r missing inject, you can inject service, constant, controller etc.. in one of two ways :

In the inject callback you can retrieve $injector and then get what you want.

var myService, location;
beforeEach(function() {
        inject(function($injector) {
            myService = $injector.get('myService');
            location = $injector.get("$location");
        });
    });

or

Get the service directly, you can add _ServiceName_ that will be resolve as ServiceName but allow you to use the ServiceName var in your test :

var scope, $rootScope, $location;
beforeEach(inject(function (_$rootScope_, _$location_) {

        scope = $rootScope.$new();
        $rootScope = _$rootScope_;
        $location = _$location_
    }));

My typical test setup is :

    beforeEach(module('MyApp'));
    beforeEach(module('MyApp.services'));
    beforeEach(module('MyApp.controllers'));

    var ctrl, scope, myService;
    beforeEach(inject(function ($rootScope, $controller, $injector) {
        scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {$scope: scope});
        myService = $injector.get('MyService');
    }));