[emberjs]what's point of adding 'on("init")' to observabes? - ember.js

I'm learning ember-cli-101. It adds on('init') when using observer. I tried to delete it , and it makes no difference.
I tried to read the api document and still make no sense, please help me out...
autoSave: function() {
var article = this.get('article');
if (!article.get('isNew')) {
this.sendAction('save', article);
}
},
stateChanged: function() {
var article = this.get('article');
if (article.get('isDirty') && !article.get('isSaving')) {
Ember.run.once(this, this.autoSave);
}
}.on('init').observes('article.state')
autoSave:.....
stateChanged: function() {
var article = this.get('article');
if (article.get('isDirty') && !article.get('isSaving')) {
Ember.run.once(this, this.autoSave);
}
}.observes('article.state')
They really works the same, what's the difference...

If the property is changed before the observer is initialized, the observer won't fire. This is why sometimes it is good to run fire the observer function also on init.

Related

Ember: How to get computed properties from a nested model?

First: I have no idea how to work with promises in Ember.js.
I want to call a property of my controller which depends on async model-data which is also nested.
Also, my model looks something like that:
+-------------+         +------------+
| Method      | hasMany |  Practice  |
|             +--------->            |
|             |         |            |
+-------------+         +------------+
                              |       
                              | hasMany
                        +-----v------+
                        | Alpha      |
                        |            |
                        |            |
                        +------------+
So I created something like this:
allAlphas: function() {
var self = this;
var returnValue = "nichts";
var promises = {
allAlphas: self.get('model.method').then(function(method) {
//get the practices
return method.get('practices');
}).then(function(practices) {
//get the alphaSField in EVERY practice
//the alphasField is the (hasmany 'alpha')member in practice
var alphasFields = practices.getEach('alphas');
return Ember.RSVP.all(alphasFields).then(function() {
return alphasFields;
});
}).then(function(alphasFields) {
// here: get all the alphas via promise or something
})
};
Ember.RSVP.hash(promises).then(function(results) {
// return all the alphas (of all pracitces in the method) in some way
});
}.property()
There are two Problems (like already metioned in the comments):
How to load nested hasMany async models like all alphas in all practices.
How to return the complete result as a property in the RSVP.hash-Method for use in templates or something
Can anybody help me?
Edit 06/20/2015
As #Kingpin2k suggested, Ive added a Gist for better understanding of my Problem:
https://gist.github.com/MarcManhart/e5c1d91e8fdfd876de37
just return an array, and populate the array after the fact.
allAlphas: function() {
var self = this,
returnValue = [];
this.get('model.method').then(function(method) {
//get the practices
return method.get('practices');
}).then(function(practices) {
//get the alphasField in EVERY practice
//the alphasField is the (hasmany 'alpha')member in practice
var alphas= practices.getEach('alphas');
Ember.RSVP.all(alphas).then(function(resolvedAlphas) {
resolvedAlphas.forEach(function(afs){
returnValue.pushObjects(afs.toArray());
});
});
});
return returnValue;
}.property()
Update
It looks like pushObjects doesn't like the ED Collection (or maybe it doesn't like the promises underneath, I didn't look into it that much). Also we should use the resolved values instead of the promises sent in (alphas vs resolvedAlphas in my code below).
Example: http://emberjs.jsbin.com/cinobetoyu/1/edit?js,output

Unit testing an AngularJS (Smart Table) directive

I am working with "Smart Table" and will be using their example plugin where a checkbox selects a row in a table: http://lorenzofox3.github.io/smart-table-website/#section-custom
I am writing a unit test for this directive, code below, this is failing. Has anyone written a unit test for this code or could help direct me as to where I am going wrong and if I am actually testing the correct logic?
Directive:
myApp.directive('csSelect', function () {
return {
require: '^stTable',
template: '',
scope: {
row: '=csSelect'
},
link: function (scope, element, attr, ctrl) {
element.bind('change', function (evt) {
scope.$apply(function () {
ctrl.select(scope.row, 'multiple');
});
});
scope.$watch('row.isSelected', function (newValue, oldValue) {
if (newValue === true) {
element.parent().addClass('st-selected');
} else {
element.parent().removeClass('st-selected');
}
});
}
};
});
Unit test:
describe('csSelect',function(){
var scope, element, attr, ctrl;
beforeEach(module('myApp.selectorresult'));
beforeEach(inject(function($rootScope, $compile) {
elm = angular.element(
'<td cs-select="row" class="ng-isolate-scope">' +
'<input type="checkbox">' +
'</td>');
scope = $rootScope;
$compile(elm)(scope);
scope.$digest();
}));
it('should create selectable input',function(){
console.log(elm.find('input'));
var checkbox = elm.find('input');
expect(checkbox.length).toBe(1);
});
});
You need to mock out the stTableController with $controllerProvider before you set up beforeEach(inject...
Check out the test spec for the pagination directive (https://github.com/lorenzofox3/Smart-Table/blob/master/test/spec/stPagination.spec.js), which also requires 'stTable'. It's a good example of how to provide the 'stTableController' with the functions you need from it.
For anyone still having this issue. I hope this helps.
I was struggling with this for ages. I tried mocking the stTableController, I tried adding the vendor files to the karma.conf.js files among other things but could not get any tests to pass.
It seemed that when I removed the require: '^stTable' the tests would pass no problem, but with it in, all tests would fail. I couldn't remove this as this would break my code.
So what I finally found was that all I had to do was add st-table to my element in the spec.js file.
So if my element was
var element = angular.element('<my-component></my-component');
I had to make it
var element = angular.element('<my-component st-table></my-component>');
After that, all tests were passing.

How do I mock an Angular service using jasmine?

This may be a duplicate but I have looked at a lot of other questions here and they usually miss what I am looking for in some way. They mostly talk about a service they created themselves. That I can do and have done. I am trying to override what angular is injecting with my mock. I thought it would be the same but for some reason when I step through the code it is always the angular $cookieStore and not my mock.
I have very limited experience with jasmine and angularjs. I come from a C# background. I usually write unit tests moq (mocking framework for C#). I am use to seeing something like this
[TestClass]
public PageControllerTests
{
private Mock<ICookieStore> mockCookieStore;
private PageController controller;
[TestInitialize]
public void SetUp()
{
mockCookieStore = new Mock<ICookieStore>();
controller = new PageController(mockCookieStore.Object);
}
[TestMethod]
public void GetsCarsFromCookieStore()
{
// Arrange
mockCookieStore.Setup(cs => cs.Get("cars"))
.Return(0);
// Act
controller.SomeMethod();
// Assert
mockCookieStore.VerifyAll();
}
}
I want mock the $cookieStore service which I use in one of my controllers.
app.controller('PageController', ['$scope', '$cookieStore', function($scope, $cookieStore) {
$scope.cars = $cookieStore.get('cars');
if($scope.cars == 0) {
// Do other logic here
.
}
$scope.foo = function() {
.
.
}
}]);
I want to make sure that the $cookieStore.get method is invoked with a 'garage' argument. I also want to be able to control what it gives back. I want it to give back 0 and then my controller must do some other logic.
Here is my test.
describe('Controller: PageController', function () {
var controller,
scope,
cookieStoreSpy;
beforeEach(function () {
cookieStoreSpy = jasmine.createSpyObj('CookieStore', ['get']);
cookieStoreSpy.get.andReturn(function(key) {
switch (key) {
case 'cars':
return 0;
case 'bikes':
return 1;
case 'garage':
return { cars: 0, bikes: 1 };
}
});
module(function($provide) {
$provide.value('$cookieStore', cookieStoreSpy);
});
module('App');
});
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller;
}));
it('Gets car from cookie', function () {
controller('PageController', { $scope: scope });
expect(cookieStoreSpy.get).toHaveBeenCalledWith('cars');
});
});
This is a solution for the discussion we had in my previous answer.
In my controller I'm using $location.path and $location.search. So to overwrite the $location with my mock I did:
locationMock = jasmine.createSpyObj('location', ['path', 'search']);
locationMock.location = "";
locationMock.path.andCallFake(function(path) {
console.log("### Using location set");
if (typeof path != "undefined") {
console.log("### Setting location: " + path);
this.location = path;
}
return this.location;
});
locationMock.search.andCallFake(function(query) {
console.log("### Using location search mock");
if (typeof query != "undefined") {
console.log("### Setting search location: " + JSON.stringify(query));
this.location = JSON.stringify(query);
}
return this.location;
});
module(function($provide) {
$provide.value('$location', locationMock);
});
I didn't have to inject anything in the $controller. It just worked. Look at the logs:
LOG: '### Using location set'
LOG: '### Setting location: /test'
LOG: '### Using location search mock'
LOG: '### Setting search location: {"limit":"50","q":"ani","tags":[1,2],"category_id":5}'
If you want to check the arguments, spy on the method
// declare the cookieStoreMock globally
var cookieStoreMock;
beforeEach(function() {
cookieStoreMock = {};
cookieStoreMock.get = jasmine.createSpy("cookieStore.get() spy").andCallFake(function(key) {
switch (key) {
case 'cars':
return 0;
case 'bikes':
return 1;
case 'garage':
return {
cars: 0,
bikes: 1
};
}
});
module(function($provide) {
$provide.value('cookieStore', cookieStoreMock);
});
});
And then to test the argument do
expect(searchServiceMock.search).toHaveBeenCalledWith('cars');
Here is an example https://github.com/lucassus/angular-seed/blob/81d820d06e1d00d3bae34b456c0655baa79e51f2/test/unit/controllers/products/index_ctrl_spec.coffee#L3 it's coffeescript code with mocha + sinon.js but the idea is the same.
Basically with the following code snippet you could load a module and substitute its services:
beforeEach(module("myModule", function($provide) {
var stub = xxx; //... create a stub here
$provide.value("myService", stub);
}));
Later in the spec you could inject this stubbed service and do assertions:
it("does something magical", inject(function(myService) {
subject.foo();
expect(myService).toHaveBeenCalledWith("bar");
}));
More details and tips about mocking and testing you could find in this excellent blog post: http://www.yearofmoo.com/2013/09/advanced-testing-and-debugging-in-angularjs.html
Why mock cookieStore when you may use it directly without modification? The code below is a partial unit test for a controller which uses $cookieStore to put and get cookies. If your controller has a method known as "setACookie" that uses $cookieStore.put('cookieName', cookieValue) ... then the test should be able to read the value that was set.
describe('My controller', function() {
var $cookieStore;
describe('MySpecificController', function() {
beforeEach(inject(function(_$httpBackend_, $controller, _$cookieStore_) {
$cookieStore = _$cookieStore_;
// [...] unrelated to cookieStore
}));
it('should be able to reference cookies now', function () {
scope.setACookie();
expect($cookieStore.get('myCookieName')).toBe('setToSomething');
});
});

How can I simulate blur when testing directives in angularjs?

The problem
I am trying to test some directives (code for both below). One of them is an "email" (called "epost" in the code(norwegian)) directive. The solution to this should work for all of them, so I am keeping it to this one for now.
Technologies: Angularjs, Jasmine, Requirejs, (grunt & karma running in Chrome)
The directive validates email addresses in two ways; on upshift and on blur. I can test the upshift without problems as you can see in the test below, but I can't figure out how to simulate a blur so the bind('blur') in the directive runs.
What I have done
I have tried to catch the compiled element like this:
elem = angular.element(html);
element = $compile(elem)($scope);
And then in the test i tried several permutations to trigger the blur with a console log just inside the bind function in the directive. None of the below works. It does not trigger.
elem.trigger('blur');
element.trigger('blur');
elem.triggerHandler('blur');
element.triggerHandler('blur');
element.blur();
elem.blur();
I based the injection and setup on this: To test a custom validation angularjs directive
The email directive in angularjs wrapped in requirejs
define(function() {
var Directive = function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var pattern = /^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
elem.bind('blur', function() {
scope.$apply(function () {
if (!elem.val() || pattern.test(elem.val())) {
ctrl.$setValidity('epost', true);
} else {
ctrl.$setValidity('epost', false);
}
});
});
ctrl.$parsers.unshift(function(viewValue) {
if (pattern.test(viewValue)) {
ctrl.$setValidity('epost', true);
return viewValue;
} else {
return undefined;
}
});
}
};
};
return Directive;
});
The test (using jasmine and requirejs)
define([
'Angular',
'AngularMocks',
], function () {
describe('Directives', function () {
var $scope;
var form;
beforeEach(module('common'));
beforeEach(function () {
var html = '<form name="form">';
html += '<input type="text" id="epost" name="epost" epost="" ng-model="model.epost"/>';
html += '</form>';
inject(function ($compile, $rootScope) {
$scope = $rootScope.$new();
$scope.model = {
epost: null
};
// Compile the element, run digest cycle
var elem = angular.element(html);
$compile(elem)($scope);
$scope.$digest();
form = $scope.form;
});
});
describe('(epost) Given an input field hooked up with the email directive', function () {
var validEmail = 'a#b.no';
var invalidEmail = 'asdf#asdf';
it('should bind data to model and be valid when email is valid on upshift', function () {
form.epost.$setViewValue(validEmail);
expect($scope.model.epost).toBe(validEmail);
expect(form.epost.$valid).toBe(true);
});
});
});
});
I have been able to figure out where I went wrong after some breakpoint debugging.
The "element" item I get out using the approach described in the top of the question is not actually the directive it self. It's an object which wraps the form and the directive.
Like this
{ 0: // The form
{ 0: // The directive (input element)
{
}
}
}
To actually simulate a blur on the directive it self, I did something like this
var directiveElement = $(element[0][0]);
directiveElement.blur();
After getting the element I wanted, and wrapping it in a jQuery object (may be optional), it worked like a charm. I then used the approach like in the test in the question with $setViewValue and checked the model value like this.
form.epost.$setViewValue('a#b.no');
directiveElement.blur();
expect($scope.model.epost).toBe('a#b.no');
expect($scope.form.epost.$valid).toBeTruthy();
Hope this could be of help to others trying to figure the directive testing out.
I too ran into a similar problem and it mystified me. My solution was to use JQuery to get the input and then use angular.element(input).triggerHandler('blur') to make it work. This is odd to me because I do not have to do this with the click event.
spyOn(controller, 'setRevenueIsInvalid');
var sugarRow = $(element).find('tr#ve_id_5')[0];
var amount = $(sugarRow).find('input.amount')[0];
angular.element(amount).triggerHandler('blur');
expect(controller.setRevenueIsInvalid).toHaveBeenCalled();

Automatic type casting of vanilla objects to Ember objects

I'm just diving in to Ember. I'm looking for a way to pass a plain array of vanilla objects into a collection/controller and have them type cast to the correct model.
Here's the simple collection view:
{{#collection id="prods" contentBinding="Vix.prodsController" tagName="ul"}}
{{content.title}}
{{/collection}}
Here's the model:
Vix.Prod = Ember.Object.extend({
id: null,
title: null
});
And the controller:
Vix.prodsController = Ember.ArrayController.create({
content: []
});
Then let's get some JSON-formatted data from the server. In this example I'll just hard-code it:
var prods = [{id:"yermom1", title:"yermom 1"}, {id:"yermom2", title:"yermom 2"}]
Vix.prodsController.set('content', prods);
So far so good. I get my simple list of li elements displaying the titles as I'd expect. But when I want to update the title of one of the objects, using:
Vix.prodsController.objectAt(0).set('title', 'new title')
It complains because the object has no set method-- it has not been properly cast to my Vix.Prod Ember Object.
Using this alternative:
Vix.prodsController.pushObjects(prods);
Produces the same result. It's only if I explicitly create new model instances that I get the get/set goodness:
var prods = [Vix.Prod.create({id:"yermom1", title:"yermom 1"}), {Vix.Prod.create(id:"yermom2", title:"yermom 2"})]
Is there a way to automatically type cast those vanilla objects to my Vix.Prod Ember Object? If not, am I the only one that really wants something like that? In Backbone one can set the model property on a collection. I suppose I can create a setter on my Controller to do something similar- just wondering if there is something built-in that I'm missing. Thanks!
No magic. I'd suggest do a loop wrapping the model.
var prods = [{id:"yermom1", title:"yermom 1"}, {id:"yermom2", title:"yermom 2"}];
for (var i = 0; i < prods.length; i++) {
prods[i] = Vix.Prod.create(prods[i]);
}
If I use ember as much as I hope to, I'm going to want a shortcut. So here's what I've done for now. I created a base Collection class that I use to create my Collections/Controllers:
Vix.Collection = Ember.ArrayController.extend({
model: null,
pushObject: function(obj) {
if (this.get('model') && obj.__proto__.constructor !== this.get('model')) {
obj = this.get('model').create(obj);
}
return this._super(obj);
},
pushObjects: function(objs) {
if (this.get('model')) {
objs = this._typecastArray(objs)
}
return this._super(objs);
},
set: function(prop, val) {
if (prop === 'content' && this.get('model')) {
val = this._typecastArray(val);
}
return this._super(prop, val);
},
_typecastArray: function(objs) {
var typecasted = [];
objs.forEach(function(obj){
if (obj.__proto__.constructor !== this.get('model')) {
obj = this.get('model').create(obj);
}
typecasted.push(obj);
}, this);
return typecasted;
}
})
Now when I call pushObject, pushObjects, or .set('collection', data), if the collection instance has a defined model property and the objects being added to the collection aren't already of that type, they'll be cast. Been working good so far, but I welcome any feedback.
You should have a look at ember-data: https://github.com/emberjs/data
It seems to fit your needs...
As of today, it's not yet production ready (as stated in the readme), but is quickly converging toward maturity, thanks to an active development.