Jasmine/Karma unit testing AngularJS service: how to mock "import" - angularjs

We have a Karma/Jasmine unit tests set up for a legacy AngularJS (v1) app (nowadays compiled with Webpack). We're trying to build unit tests for a service that uses regular Angular injections BUT also an import statement. Something like this:
import myMember from 'my-module';
(function () {
angular
.module('app.core')
.service('myService', myService);
myService.$inject = ['$window', 'anotherService'];
function myService($window, anotherService) {
...
}
})();
The import part poses a challenge because I need to mock myMember from the imported module.
First I tried testing like before, but, naturally, when I try to access myMember in any way, I get an error: "myMember is not defined"
Then I tried inserting a similar import statement at the beginning of the unit test file. However: "SyntaxError: Cannot use import statement outside a module"
Can't seem to wrap my head around this issue. Anyone got a hint how to move forward?
EDIT: The project has a complicated structure and import started working when the test file was located deeper in the directory structure. Maybe something related to file running order. Dunno. Anyways, mocking still remains a challenge.

Related

Unable to Inject $httpBackend

I am using Angular 1.5 to write mocked services for my project by following this little example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/
This is a simple code that I have written so far:
function() {
'use strict';
angular.module('agMock', ['ag', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenGET('https://localhost:8080/api/users')
.respond({user: 'fooBarBaz', roles: ['admin', 'user']});
});
})();
'ag' is the parent module of my project for which I am going to write mocks. When I try and run this, I get the error saying 'unknown provider: $httpBackend' although I have included angular.mocks library. Can anybody take a guess what can go wrong?
So I figured out why was I getting this error. The project in which I was getting this error uses gulp to inject dependencies and generate index.html files for dev and mocked environment. In the template index.html file, I had the main parent module, "äg" referenced in the ng-app.
I skipped the part where I had to substitute "agMock" instead of "ag" in the ng-app while generating mocked index. So this was the problem. Phew.

Angular is not defined Error while testing with Mocha, Chai, Sinonjs

My problem lies here where I am trying to test a controller within angular. This is the error the console throws to me when running the command mocha --compilers coffee:coffee-script/register **/*.spec.coffee to run all testing files within the project.
angular.module('weaver.ui.app');
^
ReferenceError: angular is not defined
I recently added angular-mocks library which makes sure angular is not an unresolved variable, but this doesn't resolve the problem.
My beginning of my testing file looks like this (the code is written is CoffeeScript)
# angular = require 'angular'
angular.module 'weaver.ui.app'
chai = require 'chai'
sinon = require 'sinon'
If I uncomment the require angular the error changes into the following, so I assume this is not the right way.
\npm\node_modules\angular\angular.js:29016
})(window, document);
^
ReferenceError: window is not defined
And if I remove the line angular.module 'weaver.ui.app' completely I get a similar error but this one is about the controller.
angular.module('weaver.ui.app').controller('AppDesignSidebarNewcontentCtrl', function($rootScope, $scope) {});
^
ReferenceError: angular is not defined
I hope someeone here can help me with this problem which is bugging me for quite a while now.
Please do not judge me on the name of the controller ;)

AngularJS unit testing. HttpBackend

I have AngularJS app with unit tests covering it. I added one more http request in .run part of application which checking user authentication. Now about 60% of my tests fails because they found 'unexpected http request'. Even directives tests are fail. How can I avoid running this request in tests? How can I easily mock this request in all tests? Im trying to not to put httpBackend.expect('GET', 'URL') to each test - that's too much work.
Testing with Jasmine + Karma
Thanks. I can give more details if needed.
There are a few ways to do this:
1.) Include a beforeEach that Tim Castelijns suggested but for every spec file
2.) Include the beforeEach in a separate file called app-mocks.js & include in your karma.conf.js (I'm guessing you have one).
karma.conf.js
files: [
'location/of/app-mocks.js',
'src/app/**/*.js'
],
app-mocks.js
(function () {
'use strict';
beforeEach(inject(function ($httpBackend) {
$httpBackend.whenGET('blahblahblah.com/cat/:id/food').respond('');
}));
})();
3.) Separate out user authentication logic from the core app and create an $http wrapper service (suggested). Thus you could have (simplified example):
app.js
angular.module('myApp', ['myApp.services']);
user-service.js
angular.module('myApp.services', [])
.factory('User', function ($http) {
function authenticate() {
// authenticate user
}
return {
authenticate: authenticate
};
});
and same for your directives, controllers, etc. This way, you can unit test all of your components in isolation without having to worry about intertwined logic that is actually specific to one type of functionality. Also, when you do test core app functionality, you can just mock or spy on your User service. In your spec files you would inject only the module & functionality you are testing. So instead of injecting your entire core app module, you would:
To test services
beforeEach(module('myApp.services'));
To test directives
beforeEach(module('myApp.directives'));
etc.
Of Note: When your application starts to get big, I would consider organizing your app components based on feature rather than by type as this example above does.
You can use a beforeEach block to define a call that all tests should expect
var httpBackend;
beforeEach(inject(function(_$httpBackend_) {
httpBackend = _$httpBackend_;
httpBackend.expect('GET', 'URL').respond('');
}
Note the .respond('') I added, an expect call needs this, see the documentation if you want to know why.
This beforeEach functionality comes with the widely used jasmine testing framework.

How to deal with angular module's config function when unit testing?

When setting up a unit test suite for an angular application using Karma/Jasmine, is it recommended to include the js with the app module's config function in the test's files?
I've read that it is suggested to exclude this from testing, however that seems awkward because there's often critical setup that happens in the config function that would prevent the application from working.
What's the best practice around this? Create a mock config function that does the same thing in a 'mocked' manner?
I'm running across this issue myself but want to understand the broader strategy:
How do unit test with angular-translate
In my application, I ended up using the following solution:
Define an "appBase" module with all the config and run functions that I want to run when unit-testing and create another "app" module which declares "appBase" module as a dependency and includes all the config and run functions that I don't what to run when unit-testing. Then all my unit tests use the "appBase" module, while the final application uses the "app" module. In code:
angular.module('appBase', ['dependencies'])
.config(function() {
// This one will run when unit-testing. Can also set-up mock data
// that will later be overridden by the "app" module
});
angular.module('app', ['appBase'])
.config(function() {
// This function will only run in real app, not in unit-tests.
});

Importance of order in registering provider and configuring a module in angular.js

it seems that from angular's point of view the order of registering of a service provider and the module configuration code is important: in order for the configuration code to find the provider, the provider should be registered before.
This was a total surprise for me, as I thought that angular first processes all provider registrations, to make them available for DI, and then calls config callbacks, like this:
module.config(function(myServiceProvider) {...});
Please see here a very short test that demonstrates the problem. It fails on "unknown provider", you can see it in the JS console: http://plnkr.co/edit/jGJmE2Fq7wOrwubdlTTX
Am I missing anything here? Is it an expected angular behavior?
Thanks.
Looks like this behavior has changed in more recent versions of Angular (not sure when exactly). I modified your Plunker to point from 1.0.7 to 1.3.0 and it worked without error as you had originally expected.
Similar example of code that works:
var myModule = angular.module('myModule', []);
myModule.config((myServiceProvider) => {
});
myModule.service('myService', () => {
});
Running a config for a provider before the provider is registered with the module should work just fine as you were expecting.
Reference
For reference, this reported issue appears to be the one to have fixed it: https://github.com/angular/angular.js/issues/6723
The Angular documentation for module state that:
Recommended Setup
While the example above is simple, it will not scale to large applications. Instead we recommend that you break your
application to multiple modules like this:
A service module, for service declaration
A directive module, for directive declaration
A filter module, for filter declaration
And an application level module which depends on the above modules, and which has initialization code.
As you are using a single module that you call app, you are creating a dependency between that module's config and declaration of a provider. What you should have done is to place all your providers into a separate module, such as:
var appr = angular.module('appr', [])
.provider('myService', function() {
this.$get = function() {};
})
Then you declare the dependency of your app using:
var app = angular.module('plunker', ['appr']);
Check out the updated Plunker: http://plnkr.co/edit/Ym3Nlsm1nX4wPaiuVQ3Y?p=preview
Also, instead of using the generic provider, consider using more specific implementation of provider such as controller, factory or service. Take a look at Module API documentation for more detail.

Resources