Error while executing karma tests - angularjs

I am trying to run karma unit tests for my application. The application is created using my company's custom angular yeoman generator. (The generator is very similar to the angular-yeoman generator).
I am trying to run karma jasmine test for my application. But I keep on getting the error message whenever I run grunt test
Chrome 35.0.1916 (Mac OS X 10.9.0) ERROR Uncaught object at
/Users//Dummy
Apps/karma1/app/bower_components/angular/angular.js:1611
Warning: Task "karma:unit" failed. Use --force to continue.
I have the following in my Gruntfile.js:
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
}
In karma.conf.js file I have :
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/angular*/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-bootstrap/ui-bootstrap.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'app/bower_components/service-state/js/StateService.js',
'app/scripts/controllers/dashboard.js',
'../test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
My package.json file :
{
"name": "karma1",
"version": "0.0.0",
"dependencies": {},
"devDependencies": {
"grunt": "~0.4.1",
"grunt-css": "~0.5.4",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-coffee": "~0.7.0",
"grunt-contrib-uglify": "~0.2.0",
"grunt-contrib-compass": "~0.5.0",
"grunt-contrib-jshint": "~0.6.0",
"grunt-contrib-less": "~0.9.0",
"grunt-contrib-cssmin": "~0.6.0",
"grunt-contrib-connect": "~0.5.0",
"grunt-contrib-clean": "~0.5.0",
"grunt-contrib-htmlmin": "~0.1.3",
"grunt-contrib-watch": "~0.5.2",
"grunt-autoprefixer": "~0.2.0",
"grunt-usemin": "~0.1.11",
"grunt-rev": "~0.1.0",
"grunt-shell": "~0.2.2",
"grunt-concurrent": "~0.3.0",
"load-grunt-tasks": "~0.1.0",
"grunt-google-cdn": "~0.2.0",
"grunt-ngmin": "~0.0.2",
"time-grunt": "~0.1.0",
"karma-ng-scenario": "^0.1.0",
"grunt-karma": "^0.8.3",
"karma": "^0.12.16",
"karma-ng-html2js-preprocessor": "^0.1.0",
"karma-jasmine": "^0.1.5",
"karma-chrome-launcher": "^0.1.4",
"karma-mocha": "latest",
"chai": "1.4.0",
"karma-script-launcher": "~0.1.0",
"karma-html2js-preprocessor": "~0.1.0",
"karma-requirejs": "~0.2.0",
"karma-coffee-preprocessor": "~0.1.0",
"karma-phantomjs-launcher": "~0.1.0",
"grunt-open": "~0.2.2",
"ng-midway-tester": "2.0.5"
},
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "grunt test"
}
}
My test controller is :
'use strict';
describe('Controller: DashboardCtrl', function () {
// load the controller's module
beforeEach(module('karma1App'));
var DashboardCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller,$rootScope) {
scope = $rootScope.$new();
DashboardCtrl = $controller('DashboardCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
I use REQUIREJS to load the other dependencies, but REQUIRE is used only in the directives. As a kick start I want to test my controllers and services but I keep getting this error.
Any idea what is going wrong.
Thanks!

The point I was missing that I was not loading the angular app. I am loading the angular app through a config file config.js
/* global angular */
'use strict';
var karma1App = angular.module('karma1App', [
'pascalprecht.translate', 'ngResource', 'ngRoute',
'ui.bootstrap' ]);
karma1App.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/site', {
activeTabName: 'site',
templateUrl: 'views/site.html',
controller: 'SiteCtrl'
})
.when('/Cases', {
templateUrl: 'views/Cases.html',
controller: 'CasesCtrl'
})
.when('/Cases/:caseid', {
templateUrl: 'views/Case.html',
controller: 'CaseCtrl'
})
.when('/Alarms', {
templateUrl: 'views/Alarms.html',
controller: 'AlarmsCtrl'
})
.when('/Analysis', {
templateUrl: 'views/Analysis.html',
controller: 'AnalysisCtrl'
})
.when('/Reports', {
templateUrl: 'views/Reports.html',
controller: 'ReportsCtrl'
}) /*
.when('/dashboard', {
activeTabName: 'dashboard',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
*/
.when('/admin', {
templateUrl: 'views/admin.html',
controller: 'AdminCtrl'
})
.otherwise({
redirectTo: '/site'
}); }]);
In the karma.conf.js I added this following script tag :
files: [
'app/bower_components/angular*/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-bootstrap/ui-bootstrap.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'./test/test-main.js',
'app/scripts/controllers/dashboard.js',
'../test/spec/**/*.js'
]
The test-main.js has the following line of code ONLY:
/* global angular */
'use strict';
var karma1App = angular.module('karma1App', [
'ngResource',
'ngRoute', // Angular 1.2 requires separate ngRoute
'ui.bootstrap',
'StateService'
]);
After loading the test-main.js file in the karma.conf.js file I was able to unit test my application using karma.
Hope this helps.
Thanks,
Anirban

Related

Angular 1.x Testing with Jasmine: Compiling a template not working to verify data output in template

I am trying to unit test an html template that has variables in paragraph, anchor tags, and {{header.title || translate}} however no matter what posts I have tried it does not seem to work. I get the retrieved HTML template and when it is compiled it is still the same. In the template I still see {{user}} for example. It seems none of them are actually being compiled.
Current Template Output:
<h1>{{header.title | translate}}</h1>
<h2>{{homeCtrl.name}}</h2>
Expected Output:
<h1>Cake Blogger</h1>
<h2>Alexandria</h2>
Test Suite:
(function() {
'use strict';
describe('home.tpl.html', function() {
var scope, controller, createController, template, element, rootScope;
beforeEach(module('Templates'));
beforeEach(module('mainApp'));
/**
#name: home.tpl.html
#description: Inject and set test related objects
#param {Service} rootScope - Used to get the language
#param {Compiler} $templateCache - Holding the compiled template
#param {Injector} $compile - Compiles an HTML string or DOM
*/
beforeEach(inject(
function(_$controller_, _$rootScope_, $templateCache, $compile) {
scope = _$rootScope_.$new();
createController = function() {
return _$controller_('homeCtrl', {
'$scope': scope
});
};
controller = createController();
rootScope = _$rootScope_;
template = $templateCache.get('home.tpl.html');
element = $compile(template)(rootScope);
// var ctrl = element.controller('homeCtrl');
rootScope.$digest();
console.log("home page", element);
}));
/**
#name: Describe Block - home.tpl.html
#description: Test cases related to home.tpl.html
*/
describe('home.tpl.html tests', function() {
fit('should have "Alexandria"', function() {
expect(element.html()).toContain("Alexandria");
});
});
});
})();
Karma File:
files: ['list of files'],
port: 8080,
browsers: [
'PhantomJS'
],
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor',
],
preprocessors: {
'app/**/*.tpl.html': 'html2js'
},
ngHtml2JsPreprocessor: {
'moduleName': 'Templates',
'stripPrefix': 'app/'
}
package.json
{
"name": "",
"private": true,
"devDependencies": {
"autoprefixer-core": "^5.2.1",
"grunt": "^0.4.5",
"grunt-angular-templates": "^0.5.7",
"grunt-concurrent": "^1.0.0",
"grunt-contrib-clean": "^0.6.0",
"grunt-contrib-compass": "^1.0.0",
"grunt-contrib-concat": "^0.5.0",
"grunt-contrib-connect": "^0.9.0",
"grunt-contrib-copy": "^0.7.0",
"grunt-contrib-cssmin": "^0.12.0",
"grunt-contrib-htmlmin": "^0.4.0",
"grunt-contrib-imagemin": "^1.0.0",
"grunt-contrib-jshint": "^0.11.0",
"grunt-contrib-uglify": "^0.7.0",
"grunt-contrib-watch": "^0.6.1",
"grunt-filerev": "^2.1.2",
"grunt-google-cdn": "^0.4.3",
"grunt-jscs": "^1.8.0",
"grunt-karma": "*",
"grunt-modernizr": "^1.0.2",
"grunt-newer": "^1.1.0",
"grunt-ng-annotate": "^0.9.2",
"grunt-ng-constant": "^2.0.1",
"grunt-postcss": "^0.5.5",
"grunt-svgmin": "^2.0.0",
"grunt-usemin": "^3.0.0",
"grunt-wiredep": "^2.0.0",
"jasmine-core": "^2.4.1",
"jit-grunt": "^0.9.1",
"jshint-stylish": "^1.0.0",
"karma": "^0.13.22",
"karma-coverage": "^0.5.5",
"karma-fixture": "^0.2.6",
"karma-jasmine": "*",
"karma-json-fixtures-preprocessor": "0.0.6",
"karma-json-preprocessor": "^0.3.3",
"karma-junit-reporter": "^1.2.0",
"karma-ng-html2js-preprocessor": "~0.1.0",
"karma-phantomjs-launcher": "*",
"phantomjs": "^2.1.7",
"time-grunt": "^1.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "grunt test"
},
"dependencies": {}
}
According to posts I have read such as this plunker from a post plunker example, this should be working correctly. I am thinking perhaps the controller is not binding to the scope so that when $digest runs the template cannot find the controller maybe.
Helpful Information:
Where it says rootscope.$digest() I also tried it as scope.$digest(), I also tried using $apply().
I am using ngHtml2JsPreprocessor
I am using TemplateCache
I am using $compile
Links viewed:
how to access controller in directive [jasmine]
$compile not compiling templates in Karma/Jasmine
Don't work $compile in Jasmine Karma Angular
Unit Testing AngularJS directive with templateUrl
The template returns but the angular in the template is never compiled. Always seeing {{homeCtrl.name}} instead of Alexandria.
Update 1.1
I am thinking perhaps since the translate {{header.title | translate}} is not working that maybe angular-translate (module: pascalprecht.translate) is not actually working correctly and is then causing the controller to also fail binding. Will continue investigation.
After injecting angular-translate the | translate filter just works and yields expected translated value after $compile. See this plunker as an example:
http://plnkr.co/edit/j8rbnMI067YntllwTcGi?p=preview
One possible reason that leads to your issue is timing - suppose you have big translate array / json and it takes a while to load, but Jasmine testing already starts and finishes before they are fully loaded and ready. Then Jasmine will see un-translated string during tests.
Updated 2017-06-30
After a few experiments, I can confirm that any async json loader, whether it's .useStaticFilesLoader or $.getJSON(), will not be executed before jasmine. See http://plnkr.co/edit/nreUd52iqOVvwLPMNtJA?p=preview as an example, the static loader works fine for page view but fails unit test.
One possible way to go is to ditch .useStaticFilesLoader completely. Instead, we can use grunt-replace to inject the translations during the build process. Example grunt task:
// replace string with json
replace: {
dist: {
options: {
patterns: [
{
match: /\"JSONEN\"/,
replacement: '<%= grunt.file.read("app/resources/en.json") %>'
}
]
},
files: [
{expand: true, flatten: true, src: ['app/scripts/app.js'], dest: 'public/'}
]
}
}

grunt-karma cannot find templateCache templates using grunt-angular-templates in generator-cg-angular scaffolded project Gruntfile

I used (Yeoman) generator-cg-angular to scaffold my AngularJS web-app, and I'm trying to run unit tests without using the html2js preprocessor, but alas it looks like I'm missing something.
I changed the folders tree
As per customer request, I moved index.html, app.js and app.less within a folder named app, so now the folder structure is something like the following:
|--- Gruntfile.js //the Gruntfile.js is in the root folder, just like this generator does out-of-the-box
|___dist
|___unit-test-results
|___node_modules
|___bower_components
|___app
|____app.js
|____app.less
|____index.html
|____directives
|____test-directive
|____test-directive.js
|____test-directive.less
|____test-directive.html
|____test-directive-spec.js
My karma task
karma: {
options: {
frameworks: ['jasmine'],
files: [ //this files data is also updated in the watch handler, if updated change there too
'<%= dom_munger.data.appjs %>',
'bower_components/angular-mocks/angular-mocks.js',
'<%= ngtemplates.main.dest %>',
'directive/**/*.html',
createFolderGlobs('*-spec.js')
],
logLevel:'ERROR',
reporters:['mocha','html'],
autoWatch: false, //watching is handled by grunt-contrib-watch
singleRun: true,
htmlReporter: {
outputFile: 'unit-test-results/unit-tests'+ grunt.template.today('yyyymmdd') +'.html',
// Optional
pageTitle: 'Unit Tests',
groupSuites: true,
useCompactStyle: true
}
},
all_tests: {
browsers: ['Chrome','Firefox']
},
during_watch: {
browsers: ['PhantomJS']
},
},
The test-directive-spec.js
describe('testDirective', function() {
beforeEach(module('myApp'));
beforeEach(module('directive/test-directive/test-directive.html')); //manually written
var scope,compile;
beforeEach(inject(function($rootScope,$compile) {
scope = $rootScope.$new();
compile = $compile;
}));
it('should ...', function() {
var element = compile('<test-directive></test-directive>')(scope);
scope.$digest();
expect(element.text()).toBe('hello world');
});
});
grunt test fails
When I run grunt test configured like this
grunt.registerTask('test',['dom_munger:read','karma:all_tests']);
the html report file says he the tests failed because the templates were not found
Error: [$injector:modulerr] Failed to instantiate module directive/test-directive/test-directive.html due to:
Error: [$injector:nomod] Module 'directive/test-directive/test-directive.html' 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.
So I tried adding the ngtemplates task to grunt test like this
grunt.registerTask('test',['dom_munger:read','ngtemplates','karma:all_tests']);
configuring ngtemplates like this
ngtemplates: {
main: {
options: {
module: pkg.name,
htmlmin:'<%= htmlmin.main.options %>',
url: function(url){ return url.replace('app/','')}
},
src: [createFolderGlobs('*.html'),'!'+ indexHtmlPath +'index.html','!_SpecRunner.html'],
dest: 'temp/templates.js'
}
}
and produces the following templates.js in a temp folder
angular.module('myApp').run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('directive/test-directive/test-directive.html',
"<div>hello world</div>"
);
}]);
But the html reporter still says that the templates are not found.
What am I doing so wrong?
Here's my package.json
{
"name": "myApp",
"version": "0.0.0",
"devDependencies": {
"eslint": "^3.16.1",
"eslint-config-angular": "^0.5.0",
"eslint-plugin-angular": "^1.6.1",
"grunt": "~0.4",
"grunt-angular-templates": "~0.5",
"grunt-browser-output": "0.1.0",
"grunt-contrib-clean": "~0.5",
"grunt-contrib-concat": "~0.3",
"grunt-contrib-connect": "~0.6",
"grunt-contrib-copy": "~0.5",
"grunt-contrib-cssmin": "~0.7",
"grunt-contrib-htmlmin": "~0.1",
"grunt-contrib-jshint": "~0.9",
"grunt-contrib-less": "~0.8",
"grunt-contrib-uglify": "~0.2",
"grunt-contrib-watch": "~0.6",
"grunt-dom-munger": "~3.4",
"grunt-file-exists": "^0.1.4",
"grunt-karma": "~0.8.3",
"grunt-ng-annotate": "^1.0.1",
"grunt-replace": "^1.0.1",
"grunt-timer": "^0.6.0",
"karma": "~0.12.6",
"karma-chrome-launcher": "~0.1.3",
"karma-firefox-launcher": "~0.1.3",
"karma-htmlfile-reporter": "^0.3.5",
"karma-jasmine": "~0.1.5",
"karma-mocha-reporter": "^2.2.2",
"karma-ng-html2js-preprocessor": "^1.0.0",
"karma-phantomjs-launcher": "~0.1.4",
"load-grunt-tasks": "~0.2"
}
}
After a lot of keyboard facerolling, I've come to this solution:
remove that directive/**/*.html from karma.options.files task configuration, since a) it's not enforcing project "folders-by-feature" structure and b) instead getting the templates from '<%= ngtemplates.main.dest %>' it's solid enough, you just need to change the grunt test task into grunt.registerTask('test',['dom_munger:read','ngtemplates','karma:all_tests']);
remove beforeEach(module('directive/test-directive/test-directive.html')); from test-directive-spec.js, since it looks like it clashes with the previously described ngtemplates mechanism, making the template unavaiable;

Angular Mock Inject throws error without message using Karma and Jasmine

Using the angular.mock.inject(...) function when trying to unit test an Angular (Ionic) 1 application throws the following error. The strange thing is that there is no specific error message, making particularly hard to debug. No matter what I try, it always seems to throw this same non-descript error without any message.
PhantomJS 2.1.1 (Linux 0.0.0) LoginController should pass FAILED
bower_components/angular/angular.js:4527:53
forEach#bower_components/angular/angular.js:321:24
loadModules#bower_components/angular/angular.js:4487:12
createInjector#bower_components/angular/angular.js:4409:30
WorkFn#bower_components/angular-mocks/angular-mocks.js:3160:60
loaded#http://localhost:9876/context.js:151:17
Removing the call to angular.mock.inject() allows the test to pass.
Here's the test in question:
describe('LoginController', function() {
var scope;
var controller;
beforeEach(angular.mock.module('mCommonJobs'));
beforeEach(angular.mock.inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('LoginController', {
$scope: scope
});
}));
it('should pass', function() {
expect(true).toEqual(true);
});
});
My bower dependencies:
"dependencies": {
"angular-resource": "#1.5.0",
"ionic": "driftyco/ionic-bower#1.3.2",
"ngCordova": "^0.1.27-alpha",
"ng-cordova-oauth": "^0.3.0",
"ngstorage": "^0.3.11",
"angular-mocks": "^1.5.2"
},
"resolutions": {
"angular": "~1.5.x"
}
And the files set in the Karma test config:
files: [
//Angular source
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/ionic/js/ionic.bundle.js',
'bower_components/ng-cordova-oauth/dist/ng-cordova-oauth.js',
'bower_components/ngCordova/dist/ng-cordova.js',
'bower_components/ngCordova/dist/ng-cordova-mocks.js',
'bower_components/ngstorage/ngStorage.js',
//App code
'app/**/*.module.js',
'app/**/*.js',
'app/*.js',
//Test files
'test/**/*.test.js'
],
This issue was resolved by not including all of ionic.bundle.js in the files config of karma, but by specifically including its parts.
I also explicitly forced all versions of angular-related dependencies to be the same version (special thanks to Phil in the comments.).
In the end, my bower.json had:
"dependencies": {
"angular-resource": "1.5.2",
"ionic": "driftyco/ionic-bower#1.3.2",
"ngCordova": "^0.1.27-alpha",
"ng-cordova-oauth": "^0.3.0",
"ngstorage": "^0.3.11",
"angular-mocks": "1.5.2"
},
and my karma config looked like:
files: [
//Angular source
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/ionic/js/ionic.js',
'bower_components/ionic/js/ionic-angular.js',
'bower_components/ng-cordova-oauth/dist/ng-cordova-oauth.js',
'bower_components/ngCordova/dist/ng-cordova.js',
'bower_components/ngCordova/dist/ng-cordova-mocks.js',
'bower_components/ngstorage/ngStorage.js',
//App code
'app/**/*.module.js',
'app/**/*.js',
'app/*.js',
//Test files
'test/**/*.test.js'
],

Angular Unit tests failing, not able to inject servies

this is my karma.conf.js
`use strict`;
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = wiredep({
directory: 'src/bower_components',
exclude: [],
dependencies: true,
devDependencies: true
});
return wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join(conf.paths.src, '/app/*.spec.js')
])
.concat(pathSrcHtml);
}
module.exports = function(config) {
var files=['https://maps.googleapis.com/maps/api/js?sensor=false'].concat(listFiles());
var configuration = {
files: files,
singleRun: true,
autoWatch: false,
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src ,
moduleName: 'truelocal'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
captureConsole: true,
reporters: ['progress']
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor in added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
// This block is needed to execute Chrome on Travis
// If you ever plan to use Chrome and Travis, you can keep it
// If not, you can safely remove it
// https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076
if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) {
configuration.customLaunchers = {
'chrome-travis-ci': {
base: 'Chrome',
flags: ['--no-sandbox']
}
};
configuration.browsers = ['chrome-travis-ci'];
}
config.set(configuration);
};
//Bower.json
{
"name": "truelocal",
"version": "0.0.0",
"dependencies": {
"angular": "~1.4.10",
"angular-animate": "~1.4.10",
"angular-aria": "~1.4.10",
"angular-bootstrap": "~0.13.4",
"angular-cookies": "~1.4.10",
"angular-local-storage": "~0.2.3",
"angular-messages": "~1.4.10",
"angular-resource": "~1.4.10",
"angular-sanitize": "~1.4.10",
"angular-toastr": "~1.5.0",
"angular-touch": "~1.4.10",
"animate.css": "~3.4.0",
"bootstrap": "~3.3.5",
"jquery": "~1.11.3",
"malarkey": "yuanqing/malarkey#~1.3.1",
"moment": "~2.10.6",
"moment-parseformat": "~1.1.3",
"ng-file-upload-shim": "~9.1.2",
"jQuery.dotdotdot": "~1.7.4",
"lodash": "3.10.1",
"angular-ui-router": "~0.2.18",
"markerclustererplus": "~2.1.4",
"ng-fastclick": "~1.0.2",
"angular-swipe": "~0.1.0",
"angular-bindonce": "~0.3.3",
"angular-loading-bar": "~0.9.0",
"jquery-placeholder": "~2.3.1",
"angular-shims-placeholder": "^0.4.7"
},
"devDependencies": {
"angular-mocks": "~1.4.10"
},
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.css",
"dist/fonts/glyphicons-halflings-regular.eot",
"dist/fonts/glyphicons-halflings-regular.svg",
"dist/fonts/glyphicons-halflings-regular.ttf",
"dist/fonts/glyphicons-halflings-regular.woff",
"dist/fonts/glyphicons-halflings-regular.woff2"
]
}
},
"resolutions": {
"jquery": "~1.11.3",
"angular": "^1.5.7"
}
}
This is an existing project with more than 200 Unit tests written, the code might need a bit of update but i'm not able to execute any unit test with dependent services.
I'm guessing the angular-mocks is causing an issue, if i move it up in the dependencies i dont get the module missing error. but i still dont get the other dependencies in the unit tests.
The Karma.conf.js was missing one file from the project. once all the files are fed to the test conf. tests worked like a Charm!

I am unable to make phantomjs click the signin button

I am able to have chrome click the sign in button. I am working with protractor and automating it so we can do e2e testing with phantomjs.
The html is:
<div class="form-input">
<input type="submit" id="login-button" class="btn" value="Sign in">
I have tried:
element(by.css('[class="form-input"]')).click();
element(by.css('[type="submit"]')).click();
element.all(by.id('login-button')).first().click();
element(by.id('login-button')).click();
element(by.css('[class="btn"]')).click();
element(by.css('[value="Sign in"]')).click();
element.all(by.className('form-input')).last().click();
This is my ads-e2econf.js
var fs = require('fs');
//retrieving current date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
//retrieving current time
var time = new Date();
var hour = time.getHours() + ":";
var minutes = time.getMinutes() + ":";
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
time = hour + minutes;
var results = '\nThe following Protractor tests have failed on '+ today + ' #' + time + '\n\n';
exports.config = {
capabilities: {
browserName: 'chrome',
version: '',
platform: 'ANY'
},
seleniumServerJar: 'node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',
specs: [
'test/specs/manage/*.js',
'test/specs/manage/clone/*.js',
'test/specs/regression/*.js',
'test/specs/create/create-basicAd.js',
'test/specs/create/create-pagepost.js',
'test/specs/create/create-targeting.js'
],
onPrepare: function () {
require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(console.log));
jasmine.getEnv().addReporter(new function() {
this.reportSpecResults = function(spec) {
if (!spec.results().passed()) {
results += spec.suite.description + ' ' + spec.description;
if(spec.suite.description.substring(0, 4) == 'ADS-') {
results += 'censored' + spec.suite.description;
results += 'censored';
}
results += '\n';
}
};
});
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 1000000,
isVerbose: true
},
allScriptsTimeout: 1000000,
onCleanUp: function() {
fs.writeFileSync('/tmp/results.txt', results);
}
}
This is my karma config file.
// Karma configuration
module.exports = function(config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/lodash/dist/lodash.js',
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-sanitize/angular-sanitize.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-lodash/angular-lodash.js',
'app/bower_components/angular-bootstrap/ui-bootstrap.js',
'app/bower_components/ui-utils/ui-utils.js',
'app/bower_components/angulartics/src/angulartics.js',
'app/bower_components/angulartics/src/angulartics-ga.js',
'app/bower_components/ng-csv/src/ng-csv/ng-csv.js',
'app/bower_components/angulartics/src/angulartics-ga.js',
'app/bower_components/moment/moment.js',
'app/bower_components/ng-bs-daterangepicker/src/ng-bs-daterangepicker.js',
'app/bower_components/select2/select2.js',
'app/bower_components/angular-ui-select/dist/select.js',
'app/bower_components/angular-ui-select2/src/select2.js',
'app/bower_components/bn-tokens-angular/dist/bn-tokens-angular.js',
'app/bower_components/bn-catm-angular/dist/bn-catm-angular.js',
'app/bower_components/bn-topnav/dist/js/bn-topnav.js',
'app/bower_components/angular-ui-router/release/angular-ui-router.js',
'app/bower_components/bn-expression-builder/dist/bn-expression-builder.js',
'app/bower_components/bn-appbar/dist/js/bn-appbar.js',
'app/bower_components/zeroclipboard/dist/ZeroClipboard.js',
'app/bower_components/ng-clip/dest/ng-clip.min.js',
'app/bower_components/bn.dayparting/dist/bn.dayparting.js',
'app/lib/ng-grid/build/ng-grid.js',
'app/lib/ns-popover/nsPopover.js',
'app/lib/ps-input-time.js',
'app/lib/angular-ui-scrollfix/scrollfix.js',
'app/scripts/services/facebookAPI/providers/fbcommon.js', // FML
'app/scripts/services/facebookAPI/providers/facebook.js', // FMLx2
'app/scripts/*.js',
// 'app/mock/api/api.mock.js',
// 'app/mock/api/*.mock.js',
'app/scripts/**/*.js',
'app/templates/**/*.html',
'test/unit/**/*.js'
],
// generate js files from html templates to expose them during testing.
preprocessors: {
'app/templates/**/*.html': 'html2js'
},
// list of files / patterns to exclude
exclude: [],
// web server port
port: 9010,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
//autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
//browsers: ['Chrome'],
// Timeout for capturing a browser (in ms).
captureTimeout: 60 * 1e3,
// to avoid DISCONNECTED messages
browserDisconnectTimeout : 10000, // default 2000
browserDisconnectTolerance : 1, // default 0
browserNoActivityTimeout : 60 * 1e3, //default 10000
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
This is my package.json:
{
"name": "client",
"version": "0.0.0",
"dependencies": {},
"devDependencies": {
"grunt": "^0.4.5",
"grunt-angular-templates": "^0.5.4",
"grunt-autoprefixer": "~0.4.0",
"grunt-concurrent": "~0.4.1",
"grunt-contrib-clean": "~0.5.0",
"grunt-contrib-coffee": "~0.7.0",
"grunt-contrib-compass": "~0.6.0",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-connect": "~0.5.0",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-cssmin": "~0.7.0",
"grunt-contrib-htmlmin": "~0.1.3",
"grunt-contrib-imagemin": "~0.3.0",
"grunt-contrib-jshint": "~0.7.1",
"grunt-contrib-uglify": "~0.2.0",
"grunt-contrib-watch": "~0.5.2",
"grunt-google-cdn": "~0.2.0",
"grunt-jscs": "^0.8.1",
"grunt-karma": "~0.6.2",
"grunt-newer": "~0.5.4",
"grunt-ng-constant": "^1.1.0",
"grunt-ngmin": "~0.0.2",
"grunt-protractor-runner": "~0.2.3",
"grunt-rev": "~0.1.0",
"grunt-svgmin": "~0.2.0",
"grunt-usemin": "~2.0.0",
"grunt-wiredep": "~2.0.0",
"jasmine-reporters": "~0.4.1",
"jshint-stylish": "~0.1.3",
"karma": "~0.10.9",
"karma-chrome-launcher": "~0.1.2",
"karma-coffee-preprocessor": "~0.1.2",
"karma-firefox-launcher": "~0.1.3",
"karma-html2js-preprocessor": "~0.1.0",
"karma-jasmine": "~0.1.5",
"karma-ng-html2js-preprocessor": "~0.1.0",
"karma-ng-scenario": "~0.1.0",
"karma-phantomjs-launcher": "~0.1.1",
"karma-requirejs": "~0.2.1",
"karma-script-launcher": "~0.1.0",
"load-grunt-tasks": "~0.2.0",
"phantomjs": "~1.9.7-1",
"protractor": "~2.0.0",
"requirejs": "~2.1.10",
"time-grunt": "~0.2.1"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"start": "grunt serve",
"test": "grunt test"
}
}
PhantomJS is the worst choice for e2e testing with protractor.
Even protractor core developers recommend against it:
We recommend against using PhantomJS for tests with Protractor. There
are many reported issues with PhantomJS crashing and behaving
differently from real browsers.
If you still want to solve this with PhantomJS, here is the list of things to try:
trigger click via executeScript():
browser.executeScript("arguments[0].click();", button.getWebElement());
wait for element to become clickable before making a click:
var EC = protractor.ExpectedConditions;
browser.wait(EC.elementToBeClickable(button), 5000);
maximize browser window at the startup:
browser.manage().window().maximize();
where button is an element you've found, e.g.:
var button = element(by.id("login-button"));

Resources