4

I am currently experimenting with AngularJS. I have created a simple service, which is initialized from some distant data. The url is passed as an application value.

//App declaration
angular.module('myApp', ['myApp.services']).value('someUrl', 'http://www.example.com');

//Service declaration
angular.module('myApp.services', ['someUrl']).factory('MyService', function(someUrl) {
    var data;
    "Do stuff"  
    return data;
});

Now, I am trying to unit test this, but I cannot manage to correctly set the "someUrl" parameter. I have tried things like this, without succes:

angular.module('myApp', ['myApp.services']).value('someUrl', 'test/test.json');

describe('Services', function() {
    beforeEach(module('myApp.services'));

    describe('MyService', function() {
        it('should return {success: true}', inject(function() {
            expect(data).toEqual({success: true});
        }));
    });
});

However, I always receive a "No module: someUrl" error. What is the correct syntax to initialize an app value during a unit test?

1 Answer 1

6

You setted value to "myApp" module and is testing "myApp.services" module. You should change module('myApp.services') to module('myApp').

Anyway, there is a better way to do so. You can use mock module to inject $provide so you can override any dependency.

This is how your spec would look like:

describe('Services', function() {
  // here we load the module myApp and load an additional one that
  // allows you to override your dependency
  beforeEach(module('myApp', function($provide) {
    $provide.value('someUrl', 'test/test.json');
  }));

  describe('MyService', function() {
    it('should return {success: true}', inject(function() {
        expect(data).toEqual({success: true});
    }));
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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.