Selectively Mock Services when Testing Angular with Karma - angularjs

While there have been many questions around mocking an individual Angular service in Karma, I am having an issue with making my mocks more ubiquitous throughout testing my application.
In my current setup, I have a module called serviceMocks that includes a factory with a mock of each service in the application.
Contrived example:
angular.module('serviceMocks',['ngMock'])
.factory('myServiceOne', function() {...})
.factory('myServiceTwo', function($httpBackend,$q) {...})
This works great when testing controllers and directives which may use one or more services as a dependency. I include my app's module and the serviceMocks module within my testfile, and each service is properly substituted.
beforeEach(module('myApp'));
beforeEach(module('serviceMocks'));
it('properly substitutes mocks throughout my tests', function() {...});
However, when testing a service itself I cannot include the serviceMocks module, as the service I am testing is substituted by its mock making the tests useless. However, I would still like all other services mocked as a service may depend on one or more services for its execution.
One way I thought of doing this was to make my service mocks globally available, perhaps by attaching an object to window that holds the mocks. I could then include the mocks individually when testing services like so:
beforeEach(module('myApp', function($provide) {
$provide.value('myServiceOne',window.mocks.myServiceOneMock);
$provide.value('myServiceTwo',window.mocks.myServiceTwoMock);
});
However this approach did not work, because some of the mocks use $q or other angular services to function properly, and these services are not properly injected when simply attaching the factory object to the window.
I am looking for a way to test services while having a single location to define mocks for all services. Possibilities I imagine but have been unable to succeed with:
A) Have the serviceMocks module's .run() block run before the
config stage for myApp's module. (In which case I could attach
each service to the window as the angular dependencies would be
properly injected, and inject each as shown above)
B) Be able to override the service that I'm testing with its actual implementation in the test files of each service
C) Otherwise be able to define and access these mocks globally, while still ensuring each mock has access to certain angular services such as $q.

The question contains a clue to the answer. If serviceMocks module causes design issues, using it is a mistake.
The proper pattern is to have one module per unit (mocked service in this case). ngMock is not needed, it is loaded automatically in Jasmine tests. The modules can be used one by one:
beforeEach(module('app', 'serviceOneMock', 'serviceTwoMock'));
Or joined together:
angular.module('serviceMocks', ['serviceOneMock', 'serviceTwoMock'])
There are not so many cases when serviceMocks module should exist at all. Just because a decision which services should be mocked and which should not is made for each describe block.
Most times mocked services are individual for current spec or depend on local variables. In this case the services are mocked in-place:
var promiseResult;
beforeEach(module('app'));
beforeEach(module({ foo: 'instead of $provide.value(...)' });
beforeEach(($provide) => {
$provide.factory('bar', ($q) => {
return $q.resolve(promiseResult);
}
});
...
Doing this in dedicated serviceOneMock, etc. modules may require mocked services to be refactored any moment it becomes obvious they are too generic and don't suit the case well.
If mocked service is used more than once in specs with slightly different behaviour and results in WET tests, it is better to make a helper function that will generate it for current spec rather than hard-coding it to serviceOneMock, etc. modules.

Related

Configuring shared services across multiple modules in AngularJS

My app is following John Papa's styleguide for AngularJS applications:
The styleguide emphasizes using a strongly modular approach to the design of the app. My question is about multiple configurations and their effect on shared services.
Suppose I have a main module like this:
angular.module("app", ["app.feature1"])
.config(function() {
// do some configuration here
console.log("app configured");
});
And a feature module that configures a shared angular service, let's say the $http service:
angular.module("app.feature1", [])
.config(function($http) {
// configure the $http service
console.log("feature1 configured");
});
Is my understanding correct, that the configuration by "feature1" will carry over to the main module, since the $http service is a singleton and therefore shared across modules? Or do I have to configure the $http service in the main module instead, because each module has it's own $http service instance?
Edit: I can confirm that dependency configs are carried over and are executed first. See David's jsfiddle example.
As a matter of best practice, you should configure services as early as possible, which is typically your main module (the app root), and preferably only once to avoid overlapping changes.
Since $http is a singleton (as you mentioned), any changes via configuration will be propagated throughout the application every time you inject $http.
It's also worth mentioning that configuration to services is First In First Out, meaning that if you have two configuration changes, the last-accessed configuration will be the one that is persisted to the service since the previous configuration will be overwritten if they are changing identical components of the service.
In your case, yes, the change to $http in your module will be extended to your main application and any other modules using $http.
Finally, in light of the comments, child dependency configs are resolved before parent configs, as demonstrated by this simple fiddle:
http://jsfiddle.net/maqzo6fv/
HTML:
<div ng-app="app"></div>
JS:
angular.module("app", ["app.feature1"])
.config(function() {
alert('main config');
});
angular.module("app.feature1", [])
.config(function() {
alert('child config');
});
The child config will call alert before main on every load.

Using Jamine to test an AngularJS service without mocks

I would like to use Jasmine to write tests (not unit tests) for an AngularJS service I have, which is a wrapper for a REST API I created on my server. The service call should actually get all the way to the server. No mocking needed.
I want to be able to test some scenarios involving combinations of few of these API calls.
I understand I should probably not be using angular-mocks.js but I can't figure out the syntax for getting access to the service instance in the test.
I have something like the code below. As you can see where the ?? I would like to assign the service reference to myService so I could use it in the tests.
beforeEach(function () {
module("myApp");
myService = ??
});
Also, should I include only the service file in the specRunner.html references list?
You will just need to have something like the following:
$httpBackend.whenGET(/\/your-url-here-\/.*/).passThrough();

Breezejs unit test with jasmine karma angular

I'm building an app based in Breeze and Angular
They work pretty well together but the unit test is a problem.
This is a pretty vanilla test but Breeze keeps getting in the middle:
describe('myController', function () {
beforeEach(inject(function ($injector) {
module('app');
$httpBackend = $injector.get('$httpBackend');
authRequestHandler = $httpBackend.whenGET().respond(200,
{"someStrings": ["foo", "bar"]})
//more uninteresting code...
createController = function () {
return $controller('myController', { '$scope': $rootScope });
};
}));
it('should fetch authentication token', function () {
$httpBackend.expectGET('/auth.py');
var controller = createController();
$httpBackend.flush();
});
The problem is that Breeze keeps being initialized. At execution, I receive the following message:
Error: cannot execute _executeQueryCore until metadataStore is populated.
//or,with different get: ... $httpBackend.when('GET', '/auth.py')
// .respond({ userId: 'userX' });
Error: Unexpected request: GET breeze/Breeze/Metadata No more request expected
How do I prevent or mock or stub Breeze so doesn't interfere with my tests... For instance, these tests are aimed to authentication, not data.
Breeze is not "getting in the middle" on its own. Breeze would not get involved in your $http authorization call. I'll eat my hat if you can show me that it does. You haven't shown that it does here.
But you have surfaced a very interesting point about application bootstrap design and the consequences of that design for testing.
Evidently, either your app module's start method or your controller's creation logic executes a Breeze query (perhaps both of them do). I deduce this from two facts:
The exception comes from executeQueryCore which only happens when you explicitly execute a Breeze query
You don't touch the controller in your test, neither in the beforeEach nor in the it which means these calls (and your auth call too) are made by some kind of automatic startup logic that executes before your it spec.
In your test you have taken the trouble to mock the auth call (which is in your startup logic somewhere) but not the Breeze calls.
I don't know what you actually want to test. Why would you test that the controller fetches an auth token? Is that really the controller's concern?
Perhaps you present this test merely to illustrate the problems you're having testing a controller without getting the real server involved?
Let me step back and make a more important and more general point. We must be wary of automatic startup logic whether it hides in an app module start or a controller's constructor. Be wary in particular of startup logic that involves calls to the server.
I tend to disable automated startup logic in most of my tests. I often substitute test doubles for the troublesome dependent services during my test module setup ... before calling ngMock's inject function. I make sure that the app.start method's callback ONLY uses dependent services that are easy to fake.
I you want to forge ahead using the actual dependencies by mocking the HTTP responses with $httpBackend, then you'll have to prepare $httpBackend for every request it receives from the startup code ... including the requests YOU are making with Breeze.
I'll end by reiterating that Breeze only does what you tell it to do. It is completely unaware of your direct-to-$http calls.

AngularJS $provider and $injector and bootstrapping

I've been trying to get into the nitty-gritty with angular DI and really the bootstrap process at large, and I am a bit confused as to where things really happen. In my mind, the events are in this order.
App starts.
$provider registers service providers.
In the config phase, the providers can be configured.
Now is where I am lost.
The $injector, now having access to all the configured providers from $provide, calls the constructor functions (the $get function in each provider) to instantiate service instances.
Also, if that process is correct, how does the $injector handle cases where a service depends on another service?
Services are only instantiated at the moment when they are needed, rather than during Angular's initiation. For example, if you have a controller that isn't activated yet and it depends on services which haven't yet been used, those services will be instantiated and injected whenever that controller becomes active (like changing to a view that uses it). From then on, the same instance of each service will be used.
The same is true of services that depend on other services. All dependencies of anything are resolved before it is instantiated, so if a dependency has dependencies, the same process is applied (all of that dependency's dependencies will be instantiated first, and so on).
If a circular dependency is found (service foo has a dependency that depends on service foo), Angular will throw an exception and the functionality of those services will have to be refactored into different services that will not have this kind of circular chain.

two karma jasmine tests are running at the same time conflicting on $window

I have two Jasmine describe functions in two separate files being run by Karma.
One describe function creates and tests an angularjs controller. That controller has my provider as a dependency injected into it. In the providers $get it adds an init() method to $window, e.g. $window.init = function(){}.
My other Jasmine describe function is for testing the provider. It first asserts that there is no init() method on $window. Then it creates the provider. However, the test fails: there is already an init() method on $window before the provider has been created. At first I thought how can this be. But running the test using ddescribe (with two d's) it passed. So I found the two describe functions from the two files are conflicting.
Shouldn't the tests run separately, particularly if they are testing $window? Is there a way to do this?

Resources