How to instantiate Ext views for testing in jasmine - extjs

I want to test Views in Ext4, but
Application.getView
returns constructor function, and I run out of ideas how to make it work.
describe("general", function() {
it("should have fields enabled by default", function(){
var view = Application.getView('BRM.view.business_rule.form_part.General'),
viewInstance = new view(),
items = viewInstance.items
;
_.each(items, function(item){
console.log(item);
debugger;
})
})
})

You have to use the create method:
var viewInstance = Application.getView('BRM.view.business_rule.form_part.General').create();
var items = viewInstance.items;
Alternatively you can also use Ext.create:
Ext.create('BRM.view.business_rule.form_part.General')

Related

Using angular functions ($q) in protractor

I want to use the $q service of angular in my e2e tests. (I want to get the texts of a bunch of elements via getText() which returns a promise. After all promises are resolved, I want to test the list. So I want to use $q.all() etc.)
angular.injector(['myApp']).get('$q'); results in "ReferenceError: angular is not defined"
Installing angular via node and then var angular = require("angularjs"); results in "Error: Cannot find module 'angular'"
Also, inserting a browser.waitForAngular() does not help there.
Using the inject(function($q) {}) syntax has the same problem.
How can I use such angular functions in protractor?
edit:
Here's the very naive version of what I want to achieve
var collectEntries = function(containers) {
var entries = {};
containers.each(function (container) {
var title = container.element(by.tagName('h2'));
title.getText().then(function (text) {
var key = getSomeKey();
var entry = processEntry(text);
entries[key] = entry;
});
});
return entries;
};
That works in principle, at some point in time entries contains all data. However, I need to wait for that moment. What I would do is create and return a promise that gets resolved as soon as all getText promises are resolved.
e.g.
var deferred = $q.defer();
$q.all(getTextPromises).then(function () {
deferred.resolve(entries);
});
return deferred.promise;
From the looks of your code containers is a list of elementFinders? (i.e. var containers = [element(by.x), element(by.y), element(by.z)]):
Using q: (you need to add q as dependency in package.json first)
var q = require('q');
var collectEntries = function(containers) {
var entries = {};
containers.each(function (container) {
var deferred = q.defer();
var title = container.element(by.tagName('h2'));
title.getText().then(function (text) {
deferred.resolve(processEntry(text));
});
entries[getSomeKey()] = deferred.promise();
});
return q.all(entries);
};
expect(collectEntries).toBe({key1: 'title1', key2: 'title2'})
But protractor knows promise itself (and it's preferably that you don't mix protractor's promise with q promise unless you know what you're doing):
var collectEntries = function(containers) {
var entries = {};
containers.each(function (container) {
entries[getSomeKey()] = container.element(by.tagName('h2')).
getText().then(function (text) {
return processEntry(text);
});
});
return protractor.promise.fullyResolved(entries);
};
expect(collectEntries).toBe({key1: 'title1', key2: 'title2'})
If your containers are found using a single selector (i.e. var containers = element.all(by.xyz)), it's even easier:
var collectEntries = function(containers) {
return containers.reduce(function(entries, elem) {
return elem.getText().then(function(text) {
entries[getSomeKey()] = processEntry(text);
return entries;
});
}, {});
};
expect(collectEntries).toBe({key1: 'title1', key2: 'title2'})

Backbone/Underscore _.each(...) doesn't seem to work according to docs

In this code...
_.each(this.photos, function(element,index,list) {
console.log('element...');
console.log(element);
var photoView = new PhotoView({photo:element});
self.$el.append(photoView.render());
});
element is the entire this.photos collection. Why is not just one photo element of the 10 in the collection?
EDIT: Here is my method that populates the photos collection....
loadPhotos: function(memberId) {
var self = this;
this.photos = new PhotosCollection([]);
this.photos.on('error', this.eventSyncError, this);
this.photos.fetch({
url: this.photos.urlByMember + memberId,
success: function(collection,response,options) {
console.log('Fetch photos success!');
self.render();
}
});
},
The collection loads with models just fine. In the Chrome console, I can see the collection of models. I'm not sure what's wrong. I cannot iterate the collection with any of the methods recommended by posters below.
You are using the _.each method incorrectly. The underscore methods needs to called directly on the collection:
this.photos.each(function(element,index,list) {
console.log('element...');
console.log(element);
var photoView = new PhotoView({photo:element});
self.$el.append(photoView.render());
});
Or you if want to use the _.each from you need to pass in the models property and not the collection object itself as the list:
_.each(this.photos.models, function(element,index,list) {
console.log('element...');
console.log(element);
var photoView = new PhotoView({photo:element});
self.$el.append(photoView.render());
});
One should use this.photos.each(function(elt, index, list){...}) instead of _.each(this.photos,...) because this.photos is not an underscorejs _.chain object.
Thank you for your suggestions! I would never have figured this out without all your advice above. So here was the problem...
In the parent view, this loads up photo records for a particular member...
loadPhotos: function(memberId) {
var self = this;
this.photos = new PhotosCollection([]);
this.photos.on('error',this.eventSyncError,this);
this.photos.fetch({
url: this.photos.urlByMember + memberId,
success: function(collection,response,options) {
self.render();
}
});
},
Still in the parent view, Backbone.Subviews uses this to call each child view when it renders. Note how I'm passing this.photos to the subvw-photos...
subviewCreators: {
"subvw-profile": function() {
var options = {member: this.member};
// do any logic required to create initialization options, etc.,
// then instantiate and return new subview object
return new ProfileView( options );
},
"subvw-photos": function() {
var options = {photos: this.photos};
return new PhotosView( options );
},
"subvw-comments": function() {
var options = {};
return new CommentsView( options );
}
},
This is in the subvw-photos child view. Note how the intialize is accepting the collection as a parameter. See this problem?...
initialize: function(photos) {
Backbone.Courier.add(this);
this.photos = photos;
},
render: function() {
console.log('rendering photosview now...');
var self = this;
this.photos.each(function(element,index,list) {
var photoView = new PhotoView({photo:element});
$(self.el).append(photoView.render());
});
return this;
},
I was passing an object wrapping the photos collection in to initalize but then treating it like it was just a ref to the photos collection. I had to change the subvw-photos initialize to the following...
initialize: function(args) {
Backbone.Courier.add(this);
this.photos = args.photos;
},
Then of course all the other code magically began working :-/
Thank you again for your tips! You definitely kept me on track :-)

Backbone call a model method from the view

I have a backbone app with require where I want to add a collection inside a collection with a method inside model.
I have tried to insert the method in the collection but I can't add elements.
I'd want to make a collection of app when I click an element outside the app I want add inside my app other app in a collection.
This is my app:
Model:
define(['backbone', 'collections/element'],function(Backbone, ElementCollection){
var DesignModel = Backbone.Model.extend({
initialize:function(){
console.log('Initialized Design model');
_.defaults(this, {
elements: new ElementCollection()
});
},
addElement: function(elements, options) {
return this.elements.add(elements, options);
}
});
return DesignModel;
});
Collection:
define(['backbone', 'models/design'], function(Backbone, DesignModel){
var designCollection = Backbone.Collection.extend({
model: DesignModel,
});
return designCollection;
});
View
define(['jquery' , 'backbone', 'models/design', 'collections/design', 'views/element'],
function($, Backbone, DesignModel, DesignCollection, ElementView){
var DesignView = Backbone.View.extend({
el:$('#page'),
initialize: function(){
console.log('initialize DesignView');
this.collection = new DesignCollection();
var here = this;
$('#insert-dynamic-element').click(function(){
var element = new ElementView();
here.collection.models.addElement(element);
});
},
render: function(){
}
})
return DesignView;
});
I have tried to call the function addElement in this way:
here.collection.models.addElement(element);
and
here.collection.addElement(element);
But always with error that Object has no method addElement
How can I solve this? I want to call the method addElement from the view to add an app inside another app in a collection.
Thanks
The safest way to call the method is to add the method to the collection instead of the Model. Currently the method is available on the Model instance .
So this.collection.models.addElement will not cut it
Collection
define(['backbone', 'models/design'], function(Backbone, DesignModel){
var designCollection = Backbone.Collection.extend({
model: DesignModel,
addElement: function(elements, options) {
return this.add(elements, options);
}
});
return designCollection;
});
View
define(['jquery' , 'backbone', 'models/design', 'collections/design', 'views/element'],
function($, Backbone, DesignModel, DesignCollection, ElementView){
var DesignView = Backbone.View.extend({
el:$('#page'),
initialize: function(){
console.log('initialize DesignView');
this.collection = new DesignCollection();
var here = this;
$('#insert-dynamic-element').click(function(){
var element = new ElementView();
here.collection.addElement(element);
});
},
render: function(){
}
})
return DesignView;
});
If you do not want to move the method from the current model. Then you might have to call a specific model using the index
here.collection.at(0).addElement(element);
But there might be a case when there are no model in the collection and this might lead to a error condition..
here.collection.at(0) && here.collection.at(0).addElement(element);
Well, you need to get a specific model, not the array of them. This seems like an error since you'll be picking a specific model essentially arbitrarily (unless you application has semantics that support this), but this would work:
here.collection.at(0).addElement(element);

Backbone.js - custom collection not working

In the backbone.js, for the purpose of filtering the data, i am fetching by click the element.
and i am saving the collection as newcollection. but i unable to get any data.
what is wrong with my code...
my code :
taskListPhraseI.collection = Backbone.Collection.extend({ // collection fetching
model:taskListPhraseI.model,
url : 'data/data.json',
});
taskListPhraseI.allView = Backbone.View.extend({
el:$('.boardHolder'),
events:{
'click span.green' : 'filterIt'
},
initialize:function(){
var that = this;_.bindAll(this);
this.collection = new taskListPhraseI.collection(); //initial stage i am fetching
this.collection.fetch({success:that.render});
this.on('change:filterType', this.setNewType); //on click trigger my custom method to get the collection again
//this.on('reset:filterType', this.setNewType);
},
setNewType:function(){
var newCollection = new taskListPhraseI.collection(); // my custom collection
newCollection.fetch(); // fetching
this.collection.reset(newCollection,{ silent: true }) // triggering rest
var filterType = this.filterType,
filtered = _.filter(this.collection.models, function (item) {
return item.get("dueDays") === filterType;
});
console.log(newCollection.models); // not working... why?
console.log(this.collection.models);// works
this.collection.reset(filtered);
},
or the way i am doing wrong.. to filter the collection
any one guide me a correct way of process...
thanks in advance
fetch is async. Execute your code after collection will be fetched
newCollection.fetch({context:this}).done(function() {
// your code
})
Plus this is not correct reset method usage:
this.collection.reset(newCollection,{ silent: true })
Use this way:
this.collection.reset(newCollection.toJSON(), {silent:true})
EDIT (Added example)
HTML
<button>change filter</button>
JS
var url1 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=vpetrychuk&count=9'
var url2 = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=derickbailey&count=9'
var collection = new (Backbone.Collection.extend({
url : url1,
resetWithFilter : function(key, value) {
var query = {};
query[key] = value;
this.reset(this.where(query));
}
}));
// fetch initial data
collection.fetch({dataType:'jsonp'});
$(':button').on('click', function() {
// change url and fetch another data
collection.url = url2;
collection.fetch({dataType:'jsonp'}).done(function(response) {
console.log('items count before filter:', collection.length);
// now reset collection with selected filter
collection.resetWithFilter('id_str', '294429621640912896');
console.log('items count after filter:', collection.length)
});
});
Fiddle: http://jsfiddle.net/vpetrychuk/N4ZKm/

backbone structure / collections / views passing and returning data

So I am putting together a very simple app and have got a bit stuck.
So far I have my router
var AppRouter = Backbone.Router.extend({
routes:{
"":"home"
},
initialize:function () {
// Handle back button throughout the application
$('.back').live('click', function(event) {
window.history.back();
return false;
});
this.firstPage = true;
this.products = new Products();
},
home:function () {
var view = new HomeView({collection:this.products});
// render the view when the collection is loaded
this.products.on("renderCompleted:Products", function() {
//alert("ff");
view.render();
});
// fetch should trigger "reset" when complete
this.products.fetch();
}
my model
var Product=Backbone.Model.extend({
defaults:{
id:"",
name:'',
longName:'',
productID:''
}
});
return Product;
my collection
var Products=Backbone.Collection.extend({
// Book is the model of the collection
model:Product,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
var jqxhr = $.getJSON("data/product.json")
.success(function(data, status, xhr) {
$.each(data.data.productTypeList, function(i,item){
tmpItem=new Product({id:item.id,name:item.name,longName:item.longName, productID:i});
self.add(tmpItem);
});
self.trigger("fetchCompleted:Products");
})
}
});
return Products;
and my view
var HomeView = Backbone.View.extend({
template: _.template(homeViewTemplate),
render:function (eventName) {
//$(this.el).html(this.template());
this.$el.empty();
//compile template using the data fetched by collection
this.$el.append(this.template({data:this.collection.toJSON()}));
console.log("test" + this.collection.get('data'));
return this;
}
the homeViewTemplate call has this HTML
<ul >
<% for (var i = 0; i < data.length; i++) { %>
<% var item = data[i]; %>
<li>
<%= item.longName %>
</li>
<% } %>
</ul>
you can see from the router that on init this.Products is created of the collection
then when home is called it runs the view.
I dont think anything is passed from the collection to the view though and I am not sure how this is done? Is my collection setup wrong? - do I have to call fetch and pass that to the view?
Any help is appreciated
thanks
do I have to call fetch and pass that to the view?
You have to call fetch, and have its success callback trigger view.render. You could do that using the success option of the JQuery call; or using the reset event, which collection.fetch normally calls. I'd suggest putting collection.reset inside your custom fetch:
// get the data an an array of models
var models = data.data.productTypeList.map(function(item) {
return new Product({id:item.id,name:item.name,longName:item.longName, productID:i});
});
// populate the collection
self.reset(models);
And then in the "home" route, call fetch and then call render on the callback:
home:function () {
var view = new HomeView({collection:this.products});
// render the view when the collection is loaded
this.products.on("reset", function() {
view.render();
});
// fetch should trigger "reset" when complete
this.products.fetch();
}

Resources