I have defined a empty module in angular.js:
angular.module('todoList', [], function () {
})
then I want test it, in my conf.js, I load these javascript:
files = [
JASMINE,
JASMINE_ADAPTER,
// lib
'../js/lib/angular.min.js',
'../js/lib/jquery-1.9.1.min.js',
// our app
'../js/project.js',
// test file
"test/*.js"
];
Then I want test it in test file:
describe('My own function', function(){
beforeEach(module('todoList'));
});
but this step tell me
FAILED My own function encountered a declaration exception
I don't understand why just a load module sentence would cause wrong
How can I fix this problem?
Try including angular-mocks.js in your config file.
Related
Trying to test angular services with Jest and got this error:
[$injector:nomod] Module 'superag' 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.
How do I mock my module 'superag' and make available to mathService?
Do I have to import the app.js file with the module declaration every test I make?
Ps.: I've tried with beforeEach(module('superag')) too without success
package.json
"jest": {
"collectCoverageFrom": [
"**/*.{js}",
"!**/node_modules/**"
]
},
"devDependencies": {
"angular-mocks": "^1.6.9",
"jest-cli": "^23.0.0-alpha.0"
},
"dependencies": {
"angular": "^1.6.9"
}
}
math.service.js
function MathService(){
var addTwoNumbers = function(x, y){
return x + y;
};
return {
addTwoNumbers
};
}
angular.module('superag').factory('mathservice', MathService);
math.service.test.js
require('angular');
require('angular-mocks');
require('./math.service.js');
describe('Math service - addTwoNumbers', () => {
beforeEach(
angular.mock.module('superag')
);
var _mathservice;
beforeEach(inject((mathservice) => {
_mathservice = mathservice;
}));
it('1 + 1 should equal 2', () => {
var actual = _mathservice.addTwoNumbers(1,1);
expect(actual).toEqual(2);
});
});
This error occurs when you declare a dependency on a module that isn't defined anywhere or hasn't been loaded in the current browser context.
When you receive this error, check that the name of the module in question is correct and that the file in which this module is defined has been loaded (either via <script> tag, loader like require.js, or testing harness like karma).
A less common reason for this error is trying to "re-open" a module that has not yet been defined.
To define a new module, call angular.module with a name and an array of dependent modules, like so:
// When defining a module with no module dependencies,
// the array of dependencies should be defined and empty.
var myApp = angular.module('myApp', []);
To retrieve a reference to the same module for further configuration, call angular.module without the array argument.
var myApp = angular.module('myApp');
Calling angular.module without the array of dependencies when the module has not yet been defined causes this error to be thrown. To fix it, define your module with a name and an empty array, as in the first example above.
You need to load the module under test using the module function provided in angular-mocks, so it is available in your tests, per docs.
beforeEach(module('superag'))
Then you can inject in your service.
-I've seen many questions around testing and DI, but none that has helped me so far.
I have a module:
angular
.module('app.users', ['app.auth', 'app.foo']);
and simple service with a function I want to test:
(function(){
angular
.module('app.users')
.factory('UsersModel', UsersModel);
UsersModel.$inject = ["AuthService", "FooService"]
function UsersModel(AuthService, FooService){
function someFunction(){
// do stuff...
}
}
})();
And a test file:
describe("Users", function(){
beforeEach(function(){
module('app.users');
angular.mock.module('app.auth'); // includes AuthService
angular.mock.module('app.foo'); // include FooService
})
describe("Username", function(){
it("should do stuff", inject(function(UsersModel){
// no code here
}));
});
});
Now, the service FooService itself depends on BarService. When I run this in karma, I get an error:
Unknown provider: BarServiceProvider <- BarService <- FooService <- UsersModel
And this confuses me: since I use angular.mock.module('app.foo'), I would have expected the dependencies of fooService to not even be on the radar. Apparently they are though, so I'm thinking that I'm doing something wrong.
How should I go about dealing with my service's dependencies? Should I stub FooService?
I have Done a Library Management App with Angular JS and Mongo Lab will Act as a DB Part, I am facing issuse with Require JS Dependency While Crating Unit test Case
Error: [$injector:modulerr] Failed to instantiate module lmaApp due to:
Error: [$injector:nomod] Module 'lmaApp' is not available!
The Above error I am facing,kindly help me to get out from this.
MyCode:
Controller.js
define(
['modules'],
function(lmaApp) {
lmaApp.controller('gridControl',['$scope' , '$http' , 'internal' , 'commonValues', function($scope , $http , internalFn , commonValues){
jQuery('ul.navbar-nav li').removeClass('active');
jQuery('ul.navbar-nav li:nth-child(1)').addClass('active');
$('.loaderImg').removeClass('no-loading');
var lmaTableData = internalFn.getTableData(commonValues.mongoAPIurl,commonValues.bookTableName,'');
var promise = lmaTableData
.success(function(tbData) {
if(tbData.length > 0){
$scope.nobook=0;
$scope.books =tbData;
}
else{
$scope.nobook =1;
}
}).then(function (response) {$('.loaderImg').addClass('no-loading');});
}]);
});
modules.js
define(
['app_config','angularRoute'],
function() {
var lmaApp =angular.module('lmaApp',['ngRoute'])
return lmaApp;
});
app_config.js
define(
['angular','angularRoute','modules'],
function() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['lmaApp'], {});
});
});
My spec File
controllerSpec.js
define(['angular', 'angular-mocks'], function() {
describe('gridControl', function(){
beforeEach(module('lmaApp'));
it('should get the book table Datas', inject(function($controller) {
var scope = {},
ctrl = $controller('gridControl', {$scope:scope});
expect(scope.phones.length).not.toEqual(0);
}));
});
});
Here i have a doubt with require js dependecy like i have to mention modules.js as a dependency in Spec file too.
Your controller-spec.js is wrong, you need to call its dependencies which is your module.js, app_config.js, Controller.js also 'angularRoute'. In other ot make your app to able to boostrap.
try it like this
define(['angular', 'angular-mocks','modules', 'app_config', 'Controller', 'angularRoute'], function() { ... }
Still I have nothing to be sure that it will work for you. Because if any of your configuration is wrong. It will be broken. Using requireJS with AngularJS in unit testing is very tricky/complex in the configuration.
You should read more about requireJS config, and using shim for define dependencies for your script. It will be lots clearer and eaiser to handle when your app getting bigger. For example you can do something like this in your config file:
shim: {
'modules': ['angular', 'app_config', 'angular-mocks'],
'app_config': ['angular', 'angularRoute', 'modules'],
'Controller': ['modules']
}
and your controller-spec.js will be like this
define(['modules', 'app_config', 'Controller'], function(){ ... });
Also Bootstraping angular on element ready is not a good idea for testing. It may cause some conflict in loading simulating of karma. I am not sure but don't feel right about it
Sencond Your app_config.js and modules.js are dependency of each other. So what do you think if there's something require an order in loading. Which will need to load first? since Both required the other to be loaded before it got to be injeacted by requireJS.
Still I don't think my solution will work. Because your config seem so wrong.
I try to set up angular controller unit test following this guide, the code is as follows:
describe('ProfileController', function() {
// load haloApp module
beforeEach(module('haloApp'));
it("should have notify_changed in scope", inject(function($controller) {
var scope= {},
ctrl = $controller('ProfileController', {$scope:scope});// inject controller
// expect(ProfileController).not.toBeDefined();
expect(scope.notify_changed).toBe(false);
}));
});
When I run this test case with jasmine, it report the following error:
ReferenceError: module is not defined
I have required angular file before this code snippet. Is there anything I am missing?
The module function is a part of the ngMock module defined in angular-mocks.js. Make sure that file is included when running your tests. See https://docs.angularjs.org/api/ngMock and https://docs.angularjs.org/api/ngMock/function/angular.mock.module
I'm trying to create some unit tests in Angular using Jasmine being run through Teaspoon. The tests are running, however I have a simple test just to test the existence of a controller that is failing. I have the following test setup.
//= require spec_helper
require("angular");
require("angular-mocks");
var app = require("./app");
describe("My App", function() {
describe("App Controllers", function() {
beforeEach(module("app"))
it("Should have created an application controller", inject(function($rootScope, $controller){
var scope = $rootScope.$new();
ctrl = $controller("ApplicationCtrl", { $scope: scope });
}));
})
})
The require statements are processed by Browserify which is handling my dependencies, but I can also hook into sprockets which I'm using for the spec helper.
Inside the app that is being required, I have
require("angular");
var controllers = require("./controllers");
var app = angular.module("app", [
"app.controllers"
]);
exports.app = app;
When I run this test, I get the following error produced
Failure/Error: TypeError: '[object Object]' is not a function (evaluating 'module("aialerts")')
I've spent quite a while trying to figure this out but I have no idea what's going on. Any help appreciated.
I had the same problem. Change this line:
beforeEach(module("app"))
to:
beforeEach(angular.mock.module("app"))
Browserify uses Node-style require, where module is an object that you can use to export functionality:
console.log(module); // {exports: {}}
angular-mocks.js tries to attach a function to window.module, but that's not possible in Browserify/Node.
Taking a look through the angular-mocks source, it appears that angular-mocks also attaches the module function to angular.mock. So instead of using the global module object, you must use angular.mock.module.