Karma Jasmine tests all fail after integrating ui-router - angularjs

I have a lot of tests in this app that were passing, but after integrating ui-router, every one of them fails. I am getting errors like TypeError: undefined is not an object (evaluating '$httpBackend.verifyNoOutstandingExpectation'). and TypeError: undefined is not an object (evaluating '$rootScope.$digest'). Anything that gets injected in the tests no longer works once I do the integration.
The tests only fail if I inject the $stateProvider, $stateParams or $urlRouteProvider. If I don't inject those, then they pass.
Is there some sort of configuration that I need? Does anyone know why all of a sudden all of the previous injections are non-existent?
Error Example
forEach#app/vendor/angular/angular.js:403:24
loadModules#app/vendor/angular/angular.js:4880:12
createInjector#app/vendor/angular/angular.js:4802:30
WorkFn#app/vendor/angular-mocks/angular-mocks.js:3163:60
app/vendor/angular/angular.js:4921:53
TypeError: undefined is not an object (evaluating '$rootScope.$digest') in app/core/test/sideBarDirTest.js (line 63)
app/core/test/sideBarDirTest.js:63:23
Karma Config
basePath: '',
frameworks: ['jasmine'],
files: [
'app/vendor/jquery/dist/jquery.js',
'app/vendor/angular/angular.js',
'app/vendor/angular-resource/angular-resource.js',
'app/vendor/angular-mocks/angular-mocks.js',
'app/core/app.js',
'app/core/envConfig.js',
'app/core/sideBarDir.js',
'app/core/app.js',
'app/core/test/*.js',
'**!/!*.html',
{pattern: 'app/core/**/*.json', watched: true, served: true, included: false}
],
exclude: [
'app.js',
'**/gulpfile.js'
],
reporters: ['progress', 'coverage', 'junit'],
preprocessors: {
'app/**/*.html': ['ng-html2js'],
'app/core/**/!(*Test|*test).js': 'coverage',
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/',
moduleName: 'html'
},
junitReporter: {
outputFile: 'coverage/test-results.xml',
suite: ''
},
coverageReporter: {
type: 'lcov',
dir: 'coverage/'
},
port: 9876,
colors: true,
config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
captureTimeout: 10000,
singleRun: true

I realized the root cause was just some missing modules. It seems as though my integration of ui-router required more files to be added to karma config than I thought.
When I asked this question, the error messages were very basic and that was what caused my headache. I fixed this problem by using Chrome as the browser to test with in the Karma config. This switch immediately showed me the issue. Apparently PhantomJS strips out/doesn't add the juicy parts of the error message(read: the actual Angular error).
So if you are randomly failing every test that used to pass, then I suggest that you switch to the Chrome browser to see if you aren't getting everything.

Related

How do I run karma / jasmine tests for an Angular 1.5.8 project that uses javascript, coffeescript, and typescript source?

I am working on a production system that currently uses CoffeeScript and JavaScript. We are looking to progressively migrate the source code to TypeScript in anticipation of an eventual migration to Angular 2.
I am using karma with the below karma.conf.js configuration file. As I started to add TypeScript support, I started to rapidly go down a rabbit hole of potential fixes and dead-ends. Do I need to use karma-systemjs? Can karma-systemjs handle CoffeeScript? Can karma-systemjs and browserify work together? Should I be switching to Webpack? Should I be using karma-typescript instead? If so, can it handle CoffeeScript?
The myriad options are way confusing. Any guidance would be much appreciated.
/*global module */
"use strict";
module.exports = function(config){
config.set({
basePath: '../',
files : [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-ui-bootstrap/dist/ui-bootstrap.js',
'node_modules/angular-ui-calendar/src/calendar.js',
'node_modules/angular-ui-grid/ui-grid.js',
'node_modules/angular-ui-router/release/angular-ui-router.js',
'node_modules/ui-select/dist/select.js',
'node_modules/angular-aria/angular-aria.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-material/angular-material.js',
'node_modules/angular-sanitize/angular-sanitize.js',
'node_modules/pouchdb/dist/pouchdb.js',
'app/config/**/*.js',
'app/source/**/*.js',
'test/unit/**/*.js'
],
autoWatch: true,
frameworks: ['browserify', 'jasmine'],
browsers: ['PhantomJS'],
//browsers: ['Chrome'], // Use "Chrome" for debugging since phantomjs can swallow some errors
plugins: [
'karma-browserify',
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-chrome-launcher'
],
preprocessors: {
'app/config/**/*.js': ['browserify'],
'app/source/**/*.js': ['browserify'],
'test/unit/**/*.js': [ 'browserify']
},
browserify: {
debug: true,
transform: ['coffeeify', 'babelify'],
extensions: [ ".coffee"]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};

Karma Not Running - cannot find module gulp

I'm trying to set up karma tests with Jasmine on my Angular project.
I can't get basic test
`it("dummy", function() {
expect(true).toBe(true);`
to run, and I'm getting the error:
PhantomJS 1.9.8 (Linux 0.0.0) ERROR
Error: Cannot find module 'gulp'
This is my gulp test task:
gulp.task('test', function(coverage) {
gulp.src('dummy')
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
}))
.on('error', function(err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
And this is my karma conf file:
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: ['browserify', 'jasmine'],
plugins : [
'karma-browserify',
'karma-jasmine',
'karma-phantomjs-launcher'
],
preprocessors: {
'src/app/**/*.spec.js': [ 'browserify' ],
'src/components/**/*.spec.js': [ 'browserify' ],
'src/services/**/*.spec.js': [ 'browserify' ]
},
// list of files / patterns to load in the browser
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/**/*.js',
'src/**/*.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: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
Please help me stackoverflow you're my only hope!
The most common question: did you install gulp correctly?
npm install gulp
Also check which files you are loading into the files property in karma.conf.js. There should be only your 3rd party libraries js files, your custom js files and your test files.
There's also a chance that your gulp task is not correct but since I often use grunt, I can't really help in that part :P

Karma to show Jasmine tested AngularJs code in browser

I have a working karma setup, which shows the test-results of my jasmine-tests in the console.
If I start the Jasmine SpecRunner.html I get the error "module is not defined" Therefore I added the angular-mock inside the SpecRunner-Header:
<script type="text/javascript" src='src/public/js/libs/angular/angular-mock.js'></script>
Here's my karma.config:
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
'host/test_app/lib/jasmine-2.0.0/jasmine.js',
'host/test_app/src/public/js/libs/angular/angular.min.js',
'host/test_app/src/public/js/libs/angular/angular-mock.js',
'host/test_app/spec/*.js',
'host/test_app/src/public/js/controller/*.js'
],
exclude: [ ],
preprocessors: { },
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'Firefox'],
singleRun: false
});
Is there a way to make karma show the tests with jasmines specrunner?
try using an unminified angular.js instead of angular.min.js while debugging it would give you a more meaningful error.it worked to me before.
in addition to this, if your modules are injecting asynchronously you should move your angularjs to the top because karma is working like queue while injecting them into karma config file. if im wrong, please correct me.

Understanding AngularJS testing

I seem to be unable to wrap my head around the concept of testing AngularJS applications.
I use PHPstorm as my IDE and have successfully installed node.js aswell as karma through node.
I have then created a karma.config file:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'js/angular.js',
'js/va.angular.js',
'test/**/**/*Spec.js'
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'],
captureTimeout: 60000,
singleRun: false
});
};
I have also created a test file:
// mainSpec.js
describe('controllers', function(){
beforeEach(angular.module('va'));
it('should friggin test something', inject(function() {
var x = 5;
expect(x.toBe(5));
}));
});
However, as i try to run my test, it fails due to:
TypeError: Object #<Object> has no method 'apply'
TypeError: Object 5 has no method 'toBe'
Now i have 2 questions:
What am i doing wrong here?
Where does the karma stuff get the jasmine stuff from? To me it looks like it can't get it.
Make sure you're including the angular-mocks.js module in your list of files to load.
When you specify frameworks: ['jasmine'] in the karma config, it includes jasmine so there's no need to include it yourself.
As for your error,
expect(x.toBe(5))
should be:
expect(x).toBe(5)

PhantomJS and Karma, Selector [ng\:model="query.name"] did not match any elements

When executing a karma runner using the PhantomJS browser the following error is produced:
*Selector [ng\:model="query.name"] did not match any elements*.
When executing with Chrome everything is working as expected.
Here's the line that should be matched:
`<input size='' style='width:3em;' ng-model="query.name" ng-change=changeQuery() ng-focus=focus($index) ng-blur=loseFocus($index)>`
karma.conf:
module.exports = function(config) {
config.set({
basePath: '../..',
frameworks: ['ng-scenario'],
plugins : [
'karma-ng-scenario',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-junit-reporter'
],
files: [
'test/webapp/app/e2e/*.js'
],
exclude: [
],
proxies : {
'/': 'http://localhost:19880'
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: [ 'Chrome', 'PhantomJS'],
captureTimeout: 60000,
singleRun: false
});
NodeJS version: v0.10.17
Karma version: 0.10.2
PhantomJS version: 1.9
The root cause of the failure was that the PhantomJS is built with an old version of JavaScript that is missing the "bind" implementation (Why PhantomJS doesn't have Function.prototype.bind)
The controller logic was using currying, with the bind method, and thus caused the page render incorrectly. I found this out when exporting a rendered page with the phantomJS browser.
I removed all the bind method calls from the controller code and End2end test(s) are now passing as as expected.
I apologize that from the information that I have provided for the issue, it is impossible to deduct the problem cause.

Resources