Jeremy Thake MSFT
Jeremy Thake MSFT

Reputation: 2138

The best way to Mock Services in AngularJS to decouple REST calls

I am building a web application with AngularJS and have built out a AngularJS Service that my controller uses to create, retrieve, update, delete data from. I want to farm out the UI work to another developer, but I don't want them to require the dependencies that the AngularJS Service does. I'd like to build a Mock Service and just return mock data rather than call the live REST service.

My App is set up like this:

var myApp = angular.module('myApp', ['ui.bootstrap']);

My Controller currently hooks up to the Service using:

myApp.controller('TodoCtrl', function TodoCtrl($scope, $JSOMService) {
   $JSOMService.DoStuff();
});

And my Service is defined like this

myApp.service('$JSOMService', function ($q, $http) { ... });

What the are best ways to handle switching out the service for another one? This is a little different from Unit Testing and I wondered if there are any common ways of doing this?

For now I'm just having a slightly different code base where I just switch out the Angularjs Service javascript files loaded to handle this.

Upvotes: 1

Views: 168

Answers (1)

hassassin
hassassin

Reputation: 5054

You can get access directly to the provider service, which controls injections. It would look something like this, where $provide is injected:

$provide.value('$JSOMService', MockJSOMService());

This will basically say, whenever someone asks for $JSOMService, give them whatever was returned from MockJSOMService.

You can set this up at the when you set up your app. Like this:

myApp.run(['$provide', function($provide) {
    $provide.value('$JSOMService', MockJSOMService());
}]);

This is basically how you could switch out services. Admittedly a little funky, but I hope this helps!

Upvotes: 2

Related Questions