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'
}
Related
I'm trying to get a basic unit test example working. It all works fine with this app.js
var whapp = angular.module('whapp', [])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
and this spec.js
describe('Filters', function(){ //describe your object type
beforeEach(module('whapp')); //load module
describe('reverse',function(){ //describe your app name
var reverse, rootScope;
beforeEach(inject(function($filter){ //initialize your filter
reverse = $filter('reverse',{});
}));
it('Should reverse a string', function(){ //write tests
expect(reverse('rahil')).toBe('lihar'); //pass
});
});
});
with this karma files config
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-mocks/angular-route/angular-route.js',
'node_modules/angular-mocks/angular-ui-router/release/angular-ui-router.js',
'app/js/*.js',
'tests/*.js'
]
The problem occurs when I try to inject ngRoute into my module in app.js like so
var whapp = angular.module('whapp', ['ngRoute'])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
In which case I get the following error in karma [UPDATE: this error occurs even if I don't load the angular-mock.js library into karma as shown above]
TypeError: undefined is not a constructor (evaluating 'reverse('rahil')') in tests/spec.js (line 9)
So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.
Apparently, you get this error because PhantomJS fails to instantiate your main Angular module whapp. One possible reason is, that the file node_modules/angular-mocks/angular-route/angular-route.js is missing.
Obviously, you are using npm to manage your dependencies. So try to replace your current file with:
node_modules/angular-route/angular-route.js
The same for the ui-route module:
node_modules/angular-ui-router/release/angular-ui-router.js
I hope this will help you.
I generated my web application with gulp angular. Then I created a service and want to test it.
Module file is app.module.js
angular.module('text', []);
Service file is text.service.js
(function () {
'use strict';
angular.module('text')
.factory('description',TextService);
TextService.$inject = ['$http']
function TextService($http) {
return {
QueryStaticText: queryStaticText
};
function queryStaticText(link) {
return link;
}
}
})();
Test file is text.service.spec.js
'use strict';
describe('TextService', function () {
var description;
beforeEach(function () {
module('text');
inject(function (_description_) {
description = _description_;
});
});
it('should return text', function () {
expect(description.QueryStaticText("Hello")).toEqual("Hello anu");
});
});
In the console I execute gulp test and I've got the error message
[22:02:44] Using gulpfile /Volumes/Developer/angularjs/project/gulpfile.js
[22:02:44] Starting 'test'...
[22:02:45] Starting Karma server...
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Mac OS X)]: Connected on socket 1KW_uYCk45moVKwfgAd2 with id 19804685
PhantomJS 1.9.8 (Mac OS X) ERROR
Error: [$injector:nomod] Module 'text' 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.
http://errors.angularjs.org/1.3.12/$injector/nomod?p0=text
at /Volumes/Developer/angularjs/project/bower_components/angular/angular.js:1769
/Volumes/Developer/angularjs/project/gulp/unit-tests.js:30
throw err;
The text module is not loaded, how can I load it?
It looks like you are not loading your files in order in Karma. Inside of you karma.conf.js there should be a file list. Load the app module then the rest of your javascript. Here is a post that had the same problem.
For Example:
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-animate/angular-animate.js',
'app/**/*.module.js', // Loads all files with .module.js
'app/**/*.js', // Load the rest of your .js angular files
'test/**/*.js' // Load your tests
],
Use angularFilesort to order files by dependency:
// gulp/unit-tests.js
...
// around line 36 inserted the following line:
.pipe($.angularFilesort())
So should look like:
gulp.src(srcFiles)
.pipe($.angularFilesort())
.pipe(concat(function(files) {
callback(bowerDeps.js
.concat(_.pluck(files, 'path'))
.concat(htmlFiles)
.concat(specFiles));
}))
beforeEach(module('text'));
beforeEach(inject(function (_description_) {
description = _description_;
}));
Basically, the return value of your module and injection need to be the argument for beforeEach. See https://docs.angularjs.org/guide/module#unit-testing
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)
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.
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.