Testing AngularJS Services With Dependencies

Pluralsight · 24K views · 2013 · 5:16

Open on YouTube

Testing, debugging & developer toolsWeb developmenttutorialdated

Why Stack Overflow recommends it

Stack Overflow users link it in answers about mocking dependencies and services in AngularJS tests, using Jasmine, $provide and mock objects.

Recommended by 2 people across 2 different months, 2013 to 2016.

What it is

A roughly five-minute excerpt from Pluralsight's AngularJS Fundamentals course in which Joe Eames and Jim Cooper show how to unit test an AngularJS service that has a dependency. They isolate the service by supplying a mock version of the dependency.

What people said

Recommends John Galambos · 2013-09 · Stack Overflow · on “Injecting a mock into an AngularJS service”

You can inject mocks into your service by using $provide . If you have the following service with a dependency that has a method called getSomething: angular.module('myModule', []) .factory('myService', function (myDependency) { return { useDependency: function () { return myDependency.getSomething(); } }; }); You can inject a mock version of myDependency as follows: describe('Service: myService', function () { var mockDependency; beforeEach(module('myModule')); beforeEach(function () { mockDependency = { getSomething: function () { return 'mockReturnValue'; } }; module(function ($provide) { $provide.value('myDependency', mockDependency); }); }); it('should return value from mock dependency'

Recommends Federico López · 2016-01 · Stack Overflow · on “Jasmin-Karma and mocking localStorage spyOn could not find an object to spy upon for getItem()”

I couldn't find a better way to do this than to use the $provide module in Jasmine to mock the $localStorage service as an object, since this service doesn't have any getter or setter. I was not able to use Jasmine spies in the mock, so what I did was to provide the object with the inner properties needed by the service that consumes the $localStorage service. describe("serviceThatUsengStorage", function() { "use strict"; beforeEach(angular.mock.module('myApp')); var $serviceToTest; var $localStorage = {}; var user = { uname: 'andre', pass: 'andre_pass' }; beforeEach(function() { $localStorage.user = user; module(function($provide) { $provide.value('$localStorage', $localStorage); }); }); be

Cites Braulio · 2014-06 · Stack Overflow · on “How do I mock azure mobile services in AngularJs?”

Are you accesing this services using $http or resource? Two options: - You can use a mocking framework like Sinon (we have combined it with jasmine for an angularjs based app, mocking $http request). [LINK] [this video] [LINK] - You can use angularmocks and for some given url's return harcoded values.