Unit testing custom $animate animations in karma - angularjs

I'm trying to run a unit test that tests a custom addClass animation. No matter what I try, including running samples off the web, do custom animations run in the karma test runner. NOTE my animation code works fine in a working site. I just want to be able to generate jasmine tests for my animations.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'Scripts\\angular.js',
'Scripts\\angular-animate.js',
'Scripts\\angular-mocks.js',
'Scripts\\animate-scr.js',
'Scripts\\animate-test.js',
],
exclude: [
],
reporters: ['progress'],
port: 9875,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
Here is my source code for the animation.
var counter = 0;
var testapp = angular.module('testapp', ['ngAnimate']);
testapp.counter = 2;
testapp.animation('.footeropen', function() {
return {
addClass : function(element, className) {
testapp.counter = 3;
}
};
});
And here is my unit tests code
describe('Testing Animations', function() {
beforeEach(module('testapp'));
beforeEach(module('mock.animate'));
it("should synchronously test the animation",
inject(function($animate, $rootScope) {
var element = angular.element('<div>hello</div>');
$animate.addClass(element, 'footeropen');
$rootScope.$digest();
expect(testapp.counter).toBe(3);
}));
});

Its with disappointment that I discovered that the mocked animate object actively stops custom animations on addClass() and removeClass(). The exact comment in the code is:
//There is no point in perform a class-based animation if the element already contains
//(on addClass) or doesn't contain (on removeClass) the className being animated.
//The reason why this is being called after the previous animations are cancelled
//is so that the CSS classes present on the element can be properly examined.
I have looked at running it without the mocked animate object and this causes a similar response.
So testing at this point is not possible.

Related

Angular services not being defined in beforeEach in Karma

I have an Angular Application using Jasmine and Karma for testing.
This is my testing class:
var data = require('./user.mock.js');
describe('Service: UserService', function () {
var ServerUrl;
var httpBackend;
var userService;
beforeEach(angular.mock.module('myModule'));
beforeEach(angular.mock.inject(function (_userService_, $httpBackend, _ServerUrl_) {
userService = _userService_;
httpBackend = $httpBackend;
ServerUrl = _ServerUrl_;
}));
describe('when get the active users from backend', function () {
// given
beforeEach(function () {
httpBackend
.whenGET(ServerUrl + '/users')
.respond(angular.copy(data.activeUsers));
});
it('should return the list of active users', function () {
var expectedUsers = angular.copy(data.activeUsers);
expectedUsers[0].profilePicture = ServerUrl + '/pictures/' + expectedUsers[0].id + '/small/show';
expectedUsers[1].profilePicture = ServerUrl + '/pictures/' + expectedUsers[1].id + '/small/show';
userService
.listUsers()
.then(function(users) {
expect(users).toEqual(expectedUsers);
});
httpBackend.flush();
});
});
And this is my karma conf:
// Karma configuration
// Generated on Tue May 19 2015 15:02:17 GMT+0100 (WEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: [ 'jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
// bower:js
"bower_components/jquery/dist/jquery.js",
"bower_components/angular/angular.js",
"bower_components/angular-mocks/angular-mocks.js",
"bower_components/angular-animate/angular-animate.js",
"bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
"bower_components/angular-cookies/angular-cookies.js",
"bower_components/angular-gettext/dist/angular-gettext.js",
"bower_components/angular-http-auth/src/http-auth-interceptor.js",
"bower_components/angular-notify/dist/angular-notify.js",
"bower_components/angular-resource/angular-resource.js",
"bower_components/angular-route/angular-route.js",
"bower_components/angular-sanitize/angular-sanitize.js",
"bower_components/angular-touch/angular-touch.js",
"bower_components/angular-ui-utils/ui-utils.js",
"bower_components/angular-ui-map/ui-map.js",
"bower_components/bootstrap-sass/assets/javascripts/bootstrap.js",
"bower_components/bootstrap-select/dist/js/bootstrap-select.js",
"bower_components/event-signal/dist/event-signal.min.js",
"bower_components/google-map-infobubble/src/infobubble.js",
"bower_components/moment/moment.js",
"bower_components/ng-file-upload/ng-file-upload.js",
"bower_components/ng-file-upload-shim/ng-file-upload-shim.js",
"bower_components/angularUtils-pagination/dirPagination.js",
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.html': ['ng-html2js'],
'src/**/*.js': ['browserify']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'src/',
// prepend this to the
// setting this option will create only a single module that contains templates
// from all the files, so you can load them all with module('foo')
moduleName: 'templatesForTest'
},
//
// // test results reporter to use
// // possible values: 'dots', 'progress', 'spec'
// // available reporters: https://npmjs.org/browse/keyword/karma-reporter
// reporters: ['spec'],
//
//
// // 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,
//
//
// // enable / disable watching file and executing tests whenever any file changes
// autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
When I run karma test from the command line, the services injected do not get recognized. I am suspecting that the inject function is not being called in the beforeEach method, but I am not sure. I am getting undefined in the tests, as if the variable never got any value.
workFn#/Users/brunosiqueira/WebstormProjects/copcast-admin/bower_components/angular-mocks/angular-mocks.js:2507:60
TypeError: undefined is not an object (evaluating 'httpBackend
.whenGET') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 5994)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:5994:18
TypeError: undefined is not an object (evaluating 'userService
.getUserVideos') in /var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify (line 6012)
/var/folders/pz/wmyql55d43lchz7p3jv_jmr40000gn/T/3081904ada407f95301fa9ebb665e38e.browserify:6012:18
Can you guys help me?
Two things I remember:
The order of the JS files has to be right in the config files
The usage seems grossly right and is this. Just check if this makes a
difference :
beforeEach(inject(function($controller, $rootScope, _myService_){
scope = $rootScope.$new();
myServiceSvc = _myService_;
firstCtrl = $controller("firstCtrl",{
$scope: scope,
myService: myServiceSvc
});
}));
karma.conf
files: [
'index.html',
'lib/angular.min.js',
'lib/angular-ui-router.min.js',
'lib/angular-mocks/angular-mocks.js',
'lib/app.js',
'tests/controller/basics.js'
],
In the end it just a stupid error (as most of them are).
Using git bisect, I was able to find the commit where the tests stopped working.
In that commit, I saw that I added the ng-jwplayer dependency to the project. The library requires a javascript call before it the html file.
'https://content.jwplatform.com/libraries/XXXXXX.js',
That url was missing in the karma.conf files array. It was generating an error:
files: [
'http://maps.googleapis.com/maps/api/js?sensor=false&language=en',
'https://content.jwplatform.com/libraries/XXXXXX.js',
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
'bower_components/angular-http-auth/src/http-auth-interceptor.js',
'bower_components/angular-notify/dist/angular-notify.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-ui-utils/ui-utils.js',
'bower_components/angular-ui-map/ui-map.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/bootstrap-select/dist/js/bootstrap-select.js',
'bower_components/event-signal/dist/event-signal.min.js',
'bower_components/google-map-infobubble/src/infobubble.js',
'bower_components/moment/moment.js',
'bower_components/ng-jwplayer/jwplayer.min.js',
'bower_components/ng-file-upload/ng-file-upload.js',
'bower_components/ng-file-upload-shim/ng-file-upload-shim.js',
'bower_components/angularUtils-pagination/dirPagination.js',
// endbower
'src/app/**/*.js',
'src/app/views/**/*.html',
'src/test/**/*.js'
],
With the url included, the files work well. This was another case of misleading error message.

AngularJS, Jasmine and issue writing spec tests

Okay, so I have a seed setup and I have Jasmin Running (Thank you so much SoEzPz for the help).
it appears my spec's won't run, I tried and isolated spec and it ran with no issue but when I try to write one on a controller it errors.
here is the controller.
//This is the about function that is used in the About Module.
'use strict';
app.controller('AboutController',// jshint ignore:line
['$scope',
function ($scope) {
$scope.message = 'This is the about page message from the controller';
}]);
a very basic controller
here is my test
'use strict';
describe('Controller: com/modules/AboutController', function() {
beforeEach(module('app'));
var AboutController,
scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
AboutController = $controller('AboutController', {
$scope: scope
});
}));
it('It should show the page message', function () {
expect(scope.greeting).toEqual("This is the about page message from the controller");
});
});
The spec returns this error
ReferenceError: module is not defined
at Suite.<anonymous> (http://localhost:8888/com/modules/about/aboutController_spec.js:5:16)
at addSpecsToSuite (http://localhost:8888/:801:25)
at Env.describe (http://localhost:8888/:771:7)
at jasmineInterface.describe (http://localhost:8888/:3277:18)
at http://localhost:8888/com/modules/about/aboutController_spec.js:3:1
am I missing something or is my spec written wrong ?
I am including the ngmock here is my Karma.conf file
// Karma configuration
// Generated on Tue Jul 28 2015 11:28:22 GMT-0400 (EDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../src/lib/js/angular/angular.min.js',
'../src/lib/js/angular/angular-mocks.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// 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,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
This was definitely deceptive, after playing around with the specs (thinking that the issue was in the actual specifications ) I found a test that ran fine, but still my other specs would not run, so what I did was I went back and took a hard look at my karma.conf file and while looking through some of the other examples I found I wasn't including enough in the way of bower components. so I added some more IE resources, cookies ect and low and behold all tests passed .
here is what I added under files for those who might be having the same issue
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'

ngStorage breaking my application tests

I have an Angular app with a simple karma test and a very simple configuration using requirejs and Angular 1.2.28. My test is ok.
/**
* Created by jose on 7/12/2015.
*/
/*global module, inject */
define(['home', 'angularMocks','ngStorage'], function(app) {
'use strict';
describe('homeController', function () {
var scope, $location, createController;
beforeEach(module('homeApp'));
beforeEach(inject(function ($rootScope, $controller, _$location_) {
$location = _$location_;
scope = $rootScope.$new();
createController = function () {
return $controller('homeController', {
'$scope': scope
});
};
}));
it('should have message', function () {
var controller = createController();
$location.path('/');
expect($location.path()).toBe('/');
expect(scope.message).toEqual('This is Add new order screen');
});
});
});
My module:
/**
* Created by jose on 7/12/2015.
*/
'use strict';
define(['angular', 'angularRoute'], function(angular) {
var app = angular.module('homeApp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController'
})
.when('/404', {
templateUrl: 'partials/404.html',
})
.otherwise({
redirectTo: '/404'
});
}
]);
app.controller('homeController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
return app;
});
Unfortunately, when I try to add ngStorage as a dependency for this module, it cannot works anymore. Even try to add ngStorage to my karma configuration raise an error like this:
Error: Mismatched anonymous define() module: function (app) {
It only happens when I try to use ngStorage, when I just comment it into my karma.conf file error disappears and everything works fine...
In case of not being possible using ngStorage with Karma there are another alternatives for ngStorage? thanks
karma.conf
// Karma configuration
// Generated on Mon Jul 13 2015 09:49:28 GMT-0300 (Hora est. Sudamérica Pacífico)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test-main.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/ngstorage/ngStorage.js',
{pattern: 'javascripts/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'javascripts/config.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// 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_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
Project is at github: https://github.com/jbarros35/node/tree/master/angulartemplate
kind regards.
It appears as though you are not the only one receiving errors trying to use Karma and ngStorage together. The guys at Karma have made some of their code available to help resolve the issue. You can check it out here:
https://github.com/gsklee/ngStorage/issues/117
If you look at the code of ngStorage you'll see that it calls define. So it is a proper AMD modules. Each AMD module you use in a Karma setup must be loaded with included: False in files:
{ pattern: 'bower_components/ngstorage/ngStorage.js', included: False }
Otherwise, Karma will load it with a script element, and you will get the error you got.
It's because of the async load feature of require js. Errors can be solved by this way
Go to the test-main.js.
add shim there in this way
shim:{
'yourJsModule':{
deps:['angular','yourApp']
}
}
replace "yourJsModule" with the your angular file you intend to test and the 'yourApp' with your angular module file...

How to test an Angular app?

For simple application such as just a "Hello World" where do I write tests.
I have created a plnkr.
http://plnkr.co/edit/M0GAIE837G3s1vNwTyK8?p=info
Now this is a very simple plnkr, which does nothing but display Hello World.
Now if I want to write a test for this Application i.e for MainCtrl.. where do I plug it in ?
To run test with Angular-Karma-Jasmine:
You need to install nodejs, karma runs on top of node
You need to install karma from Node Packaged Modules from your command window execute: npm install -g karma
If you plan to run this with Chrome and Firefox and you are running this on windows you need to add 2 environment variables:
CHROME_BIN = [Crome installation path/chrome.exe]
FIREFOX_BIN =[Firefox installation path/firefox.exe]
4. Go back to your project folder using the command window once there you can execute:karma init
Just hit enter until it finishes; bottom line this will create a file named: karma.config.js
In my project this file looks like this, yours probably will include some helpful comments on the different settings:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../app/*.js',
'../app/lib/angular.js',
'../app/lib/angular-route.min.js',
'../app/lib/angular-mocks.js',
'../app/app.js',
'controllers/*.js',
'services/*.js',
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome','Firefox'],
captureTimeout: 60000,
singleRun: false
});
};
Important: make sure you included angular-mocks in your configuration, the inject function is on that module.
5. Go back to your command window, navigate where your karma.config.js file is and and execute: karma start
At this point you will be good to go to start writing tests with jasmine.
a simple jasmine test for your controller will be:
describe('MainCtrl', function() {
var $scope, $rootScope, createController;
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MainCtrl', {
'$scope': $scope
});
};
}));
it('should have a...', function() {
var controller = createController();
// do your testing here...
});
});

How to configure the loading order of my Sencha Touch app files when testing with Jasmine

I would like to setup a proper testing environment for a Sencha Touch 2 app using jasmine.
I used the first three parts of this tutorial for my first steps:
https://content.pivotal.io/blog/sencha-touch-bdd-part-1
https://content.pivotal.io/blog/sencha-touch-bdd-part-2
https://content.pivotal.io/blog/sencha-touch-bdd-part-3-testing-views-and-mocking-stores
My actual problem is the following:
two config entries for two of my classes (one store and one view) need to call methods / read properties of my main app object respectively the Ext.Viewport object.
Concrete:
1.) one of my stores reads a value on the main namespace of my app (MyAppName.app.backendUrl)
Ext.define('MyAppName.store.MyStore', {
extend: 'Ext.data.Store',
config: {
model: 'MyAppName.model.MyModel',
proxy: {
type: 'ajax',
url: MyAppName.app.backendUrl + '/data.json',
reader: 'json'
},
autoLoad: true
}
});
2.) one of my views does call a method (Ext.Viewport.getOrientation()) on Ext.Viewport:
Ext.define('MyAppName.view.LoginView', {
extend: 'Ext.form.Panel',
alias: "widget.loginview",
config: {
title: 'Login',
items: [
{
xtype: 'image',
src: Ext.Viewport.getOrientation() == 'portrait' ? '../../../img/login.png' : '../../../img/login-small.png',
style: Ext.Viewport.getOrientation() == 'portrait' ? 'width:80px;height:80px;margin:auto' : 'width:40px;height:40px;margin:auto'
}
]
}
});
Unfortunately, this crashes, because both objects (MyAppName and Ext.Viewport) are not yet defined when these calls are made.
This is only the case for the testing setup (as the tutorial outlines, there is a specific app.js just for the testing). When I run the actual app in the browser (via the 'normal' app.js), this problem does not occur.
How could this be fixed (so: how can I make sure that my views/store files are run AFTER MyAppname.app and Ext.Viewport already exist)?
Thanks a lot.
I found that running Ext.application usually opens views that you typically don't want during a unit test - otherwise you're venturing into integration testing so I avoid use of the Sencha development loader. Instead I use Karma to load the unit tests and application class files. You configure these files inside the karma.conf.js file (example below).
I've adapted the examples from the excellent unit test tutorials from Pivotal Labs. Since Karma has a built in web server you don't need Rails, Rake or pow as their 1st tutorial describes. Using Karma means you can easily integrate your unit tests with Javascript tools like IntelliJ IDEA or WebStorm as well as CI systems and cloud testing like https://saucelabs.com/ . You can also configure it to watch your code files and auto rerun unit tests when you update them. You can also use karma-istanbul to perform code coverage analysis.
Using a trick I learned here, I run a setup.js file that is configured in my karma.conf.js file to load before the unit tests. It creates a fake application object so that controllers can assign themselves to an application instance and it intentionally does not have a launch() method. It also include the SpecHelper.js code from the Pivotal Labs example.
// Create (but don't launch) the app
Ext.application({name: 'MyAppName' });
For the view unit test question, you can create a fake Ext.Viewport object and add a spyOn().andReturn() to fake the Ext.Viewport.getOrientation() method required by the view during testing. This then means your unit tests can easily cover both orientation cases. You also add a renderTo: property during testing to inspect the rendered view:
describe("when portrait orientation", function() {
var view;
beforeEach(function () {
if (!Ext.Viewport) Ext.Viewport = {};
spyOn(Ext.Viewport, 'getOrientation').andReturn('portrait');
view = Ext.create('MyAppName.view.LoginView', {
renderTo: 'jasmine_content'
}
}
it("should render large image", function() {
expect(Ext.DomQuery.select('...')).toContain('img/login.png');
});
it("should render 80px style", function() {
expect(Ext.DomQuery.select('...')).toContain('80px');
});
});
View unit tests (explains how to use the renderTo property).
https://content.pivotal.io/blog/sencha-touch-bdd-part-3-testing-views-and-mocking-stores
My setup.js file show below, includes code from SpecHelper.js shown here.
You'll need this to use the renderTo property.
https://content.pivotal.io/blog/sencha-touch-bdd-part-1
Controller unit tests covers how to connect a controller to your fake application instance.
https://content.pivotal.io/blog/sencha-touch-bdd-part-5-controller-testing
setup.js
This code steals a Karma loading trick from here but unlike their example it avoids use of the development loader.
Ext.Loader.setConfig({
enabled: true, // Turn on Ext.Loader
disableCaching: false // Turn OFF cache BUSTING
});
// 'base' is set by Karma to be __dirname of karm.conf.js file
Ext.Loader.setPath({
'Ext': 'base/touch/src',
'MyAppName': 'base/app'
});
// Create (but don't launch) the app
Ext.application({name: 'MyAppName' });
Ext.require('Ext.data.Model');
afterEach(function () {
Ext.data.Model.cache = {}; // Clear any cached models
});
var domEl;
beforeEach(function () { // Reset the div with a new one.
domEl = document.createElement('div');
domEl.setAttribute('id', 'jasmine_content');
var oldEl = document.getElementById('jasmine_content');
if (oldEl) oldEl.parentNode.replaceChild(domEl, oldEl);
});
afterEach(function () { // Make the test runner look pretty
domEl.setAttribute('style', 'display:none;');
});
// Karma normally starts the tests right after all files specified in 'karma.config.js' have been loaded
// We only want the tests to start after Sencha Touch/ExtJS has bootstrapped the application.
// 1. We temporary override the '__karma__.loaded' function
// 2. When Ext is ready we call the '__karma__.loaded' function manually
var karmaLoadedFunction = window.__karma__.loaded;
window.__karma__.loaded = function () {};
Ext.onReady( function () {
console.info("Starting Tests ...");
window.__karma__.loaded = karmaLoadedFunction;
window.__karma__.loaded();
});
karma.conf.js:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// Don't use Sencha Touch dynamic loading
files: [
'touch/sencha-touch-all-debug.js',
'spec/Setup.js', // Load stubbed app - does not call app.launch()
{ pattern: 'spec/**/*.js', watched: true, served: true, included: true },
{ pattern: 'app/**/*.js', watched: true, served: true, included: false},
// Some class are not loaded by sencha-touch-all-debug.js
// this tell Karma web server that it's ok to serve them.
{ pattern: 'touch/src/**/*.*', watched: false, served: true, included: false}
],
// // Use Sencha Touch static 'testing' app.js
// files: [
// './build/testing/PT/app.js',
// './spec/SetUp.js',
// './spec/**/*.js'
// ],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.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
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install
// karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install
// karma-ie-launcher`)
//browsers: [ 'PhantomJS' ],
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
You need to spec/javascripts/support/jasmime.yml the files you need in the right order :
src_files:
- touch/sencha-touch-all-debug.js # Load Sencha library
- spec/app.js # Load our spec Ext.Application
- app/util/Urls.js #custom dependency
- app/**/*.js # Load source files
One way to get around the problem would be to define items from initComponent. That way it won't be called until instantiated, instead of at startup.
Ext.define('MyAppName.view.LoginView', {
extend: 'Ext.form.Panel',
alias: "widget.loginview",
config: {
title: 'Login'
},
initComponent: function() {
this.items = [
{
xtype: 'image',
src: Ext.Viewport.getOrientation() == 'portrait' ? '../../../img/login.png' : '../../../img/login-small.png',
style: Ext.Viewport.getOrientation() == 'portrait' ? 'width:80px;height:80px;margin:auto' : 'width:40px;height:40px;margin:auto'
}
];
this.callParent();
}
});
And the same thing for the store, but in the constructor
Ext.define('MyAppName.store.MyStore', {
extend: 'Ext.data.Store',
config: {
model: 'MyAppName.model.MyModel',
autoLoad: true
},
constructor: function(cfg) {
this.proxy = {
type: 'ajax',
url: MyAppName.app.backendUrl + '/data.json',
reader: 'json'
};
this.callParent(arguments)
}
});

Resources