0

This is my service

angular.module('providers',)
    .provider('sample', function(){

        this.getName = function(){
            return 'name';
        };
        this.$get = function($http, $log, $q, $localStorage, $sessionStorage) {
            this.getTest = function(){
                return 'test';
            };
        };
    });

This is my unit test

describe('ProvideTest', function() 
{
    beforeEach(module("providers"));
    beforeEach(function(){
      module(function(sampleProvider){
        sampleProviderObj=sampleProvider;
      });
    });
    beforeEach(inject());

     it('Should call Name', function()
    {
        expect(sampleProviderObj.getName()).toBe('name');   
    });

    it('Should call test', function()
    {
        expect(sampleProviderObj.getTest()).toBe('test');

    });


});

I am getting an error Type Error: 'undefined' is not a function evaluating sampleProviderObj.getTest()

I need a way to access function inside this.$get . Please help

2 Answers 2

1

You should inject your service into the test. Replace this:

beforeEach(function(){
  module(function(sampleProvider){
    sampleProviderObj=sampleProvider;
  });
});
beforeEach(inject());

With this:

beforeEach(inject(function(_sampleProvider_) {
    sampleProvider = _sampleProvider_;
  }));
Sign up to request clarification or add additional context in comments.

Comments

1

Firstly, you need, as had already been said, inject service, that you test. Like following

beforeEach(angular.mock.inject(function ($injector) {
    sampleProviderObj = $injector.get('sample');
}));

Second, and more important thing. Sample have no any getTest functions. If you really need to test this function, you should as "Arrange" part of your test execute also $get function of your provider. And then test getTest function of result of previous execution. Like this:

it('Should call test', function()
{
    var nestedObj = sampleProviderObj.$get(/*provide correct parameters for this function*/)
    expect(nestedObj.getTest()).toBe('test');
});

But it's not good because this test can fail even if nestedObj.getTest work properly (in case when sampleProviderObj.$get works incorrect).

And one more thing, it seems like you need to inject this services $http, $log, $q, $localStorage, $sessionStorage to you provider rather then passing them as parameters.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.