I'm using angular full stack for development, my karma.conf.js file is
files: [
'app/bower_components/jquery/jquery.js',
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-scenario/angular-scenario.js',
'app/scripts/controllers/*.js',
'app/scripts/directives/*.js',
'app/scripts/services/*.js',
'app/scripts/app.js',
'lib/routes.js',
'test/karma/unit/**/test.spec.js'
],
Test Spec:
'use strict';
(function() {
describe('App', function() {
describe('TestController', function() {
beforeEach(function() {
this.addMatchers({
toEqualData: function(expected) {
return angular.equals(this.actual, expected);
}
});
});
// Load the controllers module
beforeEach(module('ratefastApp'));
// Initialize the controller and a mock scope
var TestController,
mockUserResource,
scope,
$httpBackend,
$routeParams,
$location;
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(
inject(function($controller, $rootScope, _$location_, _$routeParams_, _$httpBackend_) {
scope = $rootScope.$new();
TestController = $controller('TestController', {
$scope: scope
});
$routeParams = _$routeParams_;
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/api/test/page/:pagenum')
.respond([{title: 'test'}]);
$location = _$location_;
}));
});
});
});
On running the above I'm getting $injector:nomod Module is not available.
The module(s) needs to be loaded in your karma files before the rest of the application.
This is because "Calling angular.module without the array of dependencies when the module has not yet been defined causes this error to be thrown" docs.angularjs.org. Therefore, you must explicitly load the files before the rest of your application.
In your Karma.config javascript files:
'app/bower_components/jquery/jquery.js',
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-scenario/angular-scenario.js',
'app/scripts/app.js', // Load your module before the rest of your app.
'app/scripts/controllers/*.js',
'app/scripts/directives/*.js',
'app/scripts/services/*.js',
'lib/routes.js',
'test/karma/unit/**/test.spec.js'
This error indicates that some module is not being found. Specifically the source for loader.js seems to show that this error gets thrown when you haven't registered a module with angular.module. Have you done so with ratefastApp? Here's the copied source:
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
Also, Since you are trying to inject $controller, $rootScope, _$location_, _$routeParams_, _$httpBackend_, with the mock $inject, I'd start by ensuring you have the files containing those services in your karma.conf.js files directive. You may also want to use wildcards to include all angular files.
Related
I have a unit test that is created with the Jasmine framework. When I put a single test specification in the describe block I get a pass in the karma console. If I copy that describe block with the test in it ( the it(); ) then I suddenly start getting problems with dependencies that the module uses.
In the console I get errors around unknown providers.
Here is my simple test:
describe('service definition tests', function () {
it('should be defined', function () {
expect(sut).toBeDefined();
});
});
and that passes okay. If I copy this block I get an error about dependencies. Which is strange as I've already proved that I can test the 'sut' is defined in the first test.
One thing to note is that I have a beforeEach block that loads the module and provides a dependency and it is this dependency that errors when I've duplicated the test. Here is the beforeEach:
var mockConfig = {};
beforeEach(function () {
module('app');
module(function ($provide) {
$provide.value('myConfig', mockConfig);
});
});
the problem has to be something to do with this beforeEach being as the error I get is about the myConfig dependency.
Here is the error:
uncaught Error: [$injecor:unpr] Unknown provider: myConfigProvider <- myConfig <- authorisation
http://errors.angularjs.org/1.4.6/$injector/unpr?p0=myConfiProvider
I managed to resolve this issue by creating a dummy implementation of myConfig factory so that the test files used this.
angular.module('app').factory('myConfig', function() {
var env = 'test';
return {
env: env
}
});
This code lives in a js file that is loaded with the rest of the tests.
I am new to Mocha and AngularJS Unit Testing but want to test my application using Mocha. I have basic language tests working, but I cannot run tests against my applications Factory or Controller.
I have the following basic files.
apps.js
aangular.module('MyApp', []);
file1.js
angular.module('MyApp').factory('Factory1' ...);
file2.js
angular.module('MyApp').factory('Factory2' ...);
angular.module('MyApp').factory('Controller' ...);
describe('Main Test', function() {
var FactoryToTest;
beforeEach(module('MyApp'));
beforeEach(inject(function (_Factory_) {
FactoryToTest = _Factory_;
}));
describe('Factory2', function () {
it('should return "unknown"', function () {
Game = {};
expect(new Factory2(Game)).to.equal('unknown');
});
});
});
When I run the test, it generates an error, and I am not sure what to fix to get this to work.
Error:
Message:
object is not a function
Stack:
TypeError: object is not a function
at Suite.<anonymous> (b:\app\test.js:5:16)
You're getting an error because the beforeEach function should take a callback function instead of an object. According to the Angular guide on module unit testing (scroll to bottom of the page) :
Each module can only be loaded once per injector. Usually an Angular app has only one injector and modules are only loaded once. Each test has its own injector and modules are loaded multiple times.
I am trying to write some unit tests for an AngularJS service. I want to run the unit tests from the command-line via Grunt. In an attempt to do that, I've written the following:
gruntfile.js
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jasmine: {
service: {
src: 'dist/myService.js',
options: {
specs: 'test/*.js',
vendor: [
'bower_components/angularjs/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js'
]
}
}
}
});
// load all grunt task details
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jasmine:service']);
};
dist/myService.js
'use strict';
angular.module('myModule')
.factory('$myService', function () {
return {
getResult: function () {
return 3;
}
};
})
;
test/serviceTests.spec.js
describe('myModule', function() {
beforeEach(function() {
console.log('loading module...');
module('myModule');
});
describe('$myService', function () {
it('should work', function () {
console.log('testing');
expect(1 + 2).toEqual(3);
});
});
})
When I try to run this, I get the following error:
Running "jasmine:service" (jasmine) task
Testing jasmine specs via PhantomJS
>> Error: [$injector:nomod] http://errors.angularjs.org/1.2.22/$injector/nomod?p0=myModule at
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:20
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:21
>> ..\..\..\C:\source\myModule\dist\myService.js
myModule
$myService
- should work...
log: loading module...
log: testing
√ should work
I know that in order to test my service, I need to inject it. However, at this time, I'm getting an error loading the module itself. For that reason, I know that I cannot inject my service. However, I do not know why the module won't load. I've confirmed that I have the correct src value.
Can anybody tell me what I'm doing wrong? Or, perhaps point me to the smallest possible example of testing a service in AngularJS (complete with Grunt, etc.)?
I just don't understand what is wrong with my approach. Thank you for your help.
When you call angular.module('myModule') (without second parameter) Angular tries to reference already existing module and cannot find it.
To declare a new module you should call angular.module('myModule', []) (with two parameters)
When running grunt karma, a test on one of the directive fails when it tries to fetch the template. I am using ng-html2js as a preprocessor. Here is some of my karma.conf.js
plugins: ['karma-chrome-launcher',
'karma-jasmine',
'ng-html2js',
'karma-ng-html2js-preprocessor'],
preprocessors: {
'app/scripts/directives/**/*.html': 'ng-html2js'
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
}
In my test, I have the following:
'use strict';
describe('Directive: myDirective', function () {
// load the directive's module
beforeEach(module('myApp'));
beforeEach(module('templates'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should not show search area initially', inject(function ($compile) {
element = angular.element('<navbar></navbar>');
element = $compile(element)(scope);
scope.$digest();
expect(element.find('.myClass').hasClass('myClass')).toBe(true);
}));
});
When I run the test, I get
Error: Unexpected request: GET /scripts/directives/myDirective/myDirective.html
It seems like the preprocessor is not properly injecting the javascript version of the template.
I have also tried using the path of the template in the beforeEach(module('')); but that causes an error that reads:
Error: [$injector:modulerr] Failed to instantiate module...
How can I fix this?
I had kind of the same problem. Be sure you have the exact file match. Open the Google chrome console and check the file path is exactly the same.
In the upper exemple, I had to add a "/" string in ngHtml2JsPreprocessor.stripPrefix and it worked.
So I guess with Yeoman, you should use
ngHtml2JsPreprocessor: {
moduleName: 'templates',
stripPrefix: 'app/' //add a slash
}
Since I was using the Yeoman tool to scaffold my project, I needed to add a stripPrefix to the ngHtml2JsPreprocessor option in my karma.conf.js file:
ngHtml2JsPreprocessor: {
moduleName: 'templates',
stripPrefix: 'app'
}
My angular app worked great and so did my tests, using karma and jasmine, until I added a dependency in ui.bootstrap. Now the app still works as expected, but I can't get my tests to run. This is what I have:
app.js - added dependency in ui.bootstrap
angular.module('myApp', ['ngResource', 'ngRoute', 'ui.bootstrap']).config(function(...) {...});
service.js
angular.module('myApp').service('myService', function () {})
controller.js
angular.module('myApp').controller('MyController', function ($scope, $http, myService) {})
tests/main.js
describe('Controller: MyController', function () {
var MyController, scope;
// load the controller's module
beforeEach(function(){
module('myApp');
inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MyController = $controller('MyController', {
$scope:scope
});
});
});
it('should do something', function () {
expect(scope.myOptions.length).toBe(5);
});
});
And my test, which I run using grunt and krama, fails due to:
Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
Error: [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot
What have I missed? The app runs with no problem, only the test fails.
In karma.conf.js there is a list of files that karma loads before test execution:
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
...
]
Add bootstrap-ui.js there.
Inject your dependencies
beforeEach(function(){
angular.module('ui.bootstrap',[]);
});
I had the same problem. Just solved it. Somehow putting the module(myApp); function call inside a the function you provide to beforeEach() doesn't work just try this:
Extract the module call into its own beforeEach():
beforeEach(module('myApp'));
And use another beforeEach() for the function you use.