How to do Ember integration testing for route transitions? - ember.js

I'm having a problem doing integration testing with ember using Toran Billup's TDD guide.
I'm using Karma as my test runner with Qunit and Phantom JS.
I'm sure half of if has to do with my beginner's knowledge of the Ember runloop. My question is 2 parts:
1) How do I wrap a vist() test into the run loop properly?
2) How can I test for transitions? The index route ('/') should transition into a resource route called 'projects.index'.
module("Projects Integration Test:", {
setup: function() {
Ember.run(App, App.advanceReadiness);
},
teardown: function() {
App.reset();
}
});
test('Index Route Page', function(){
expect(1);
App.reset();
visit("/").then(function(){
ok(exists("*"), "Found HTML");
});
});
Thanks in advance for any pointers in the right direction.

I just pushed up an example application that does a simple transition when you hit the "/" route using ember.js RC5
https://github.com/toranb/ember-testing-example
The simple "hello world" example looks like this
1.) the template you get redirected to during the transition
<table>
{{#each person in controller}}
<tr>
<td class="name">{{person.fullName}}</td>
<td><input type="submit" class="delete" value="delete" {{action deletePerson person}} /></td>
</tr>
{{/each}}
</table>
2.) the ember.js application code
App = Ember.Application.create();
App.Router.map(function() {
this.resource("other", { path: "/" });
this.resource("people", { path: "/people" });
});
App.OtherRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('people');
}
});
App.PeopleRoute = Ember.Route.extend({
model: function() {
return App.Person.find();
}
});
App.Person = Ember.Object.extend({
firstName: '',
lastName: ''
});
App.Person.reopenClass({
people: [],
find: function() {
var self = this;
$.getJSON('/api/people', function(response) {
response.forEach(function(hash) {
var person = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, person);
});
}, this);
return this.people;
}
});
3.) the integration test looks like this
module('integration tests', {
setup: function() {
App.reset();
App.Person.people = [];
},
teardown: function() {
$.mockjaxClear();
}
});
test('ajax response with 2 people yields table with 2 rows', function() {
var json = [{firstName: "x", lastName: "y"}, {firstName: "h", lastName: "z"}];
stubEndpointForHttpRequest('/api/people', json);
visit("/").then(function() {
var rows = find("table tr").length;
equal(rows, 2, rows);
});
});
4.) the integration helper I use on most of my ember.js projects
document.write('<div id="foo"><div id="ember-testing"></div></div>');
Ember.testing = true;
App.rootElement = '#ember-testing';
App.setupForTesting();
App.injectTestHelpers();
function exists(selector) {
return !!find(selector).length;
}
function stubEndpointForHttpRequest(url, json) {
$.mockjax({
url: url,
dataType: 'json',
responseText: json
});
}
$.mockjaxSettings.logging = false;
$.mockjaxSettings.responseTime = 0;

I'm unfamiliar with Karma, but the portions of your test that needs to interact with ember should be pushed into the run loop (as you were mentioning)
Ember.run.next(function(){
//do somethin
transition stuff here etc
});
To check the current route you can steal information out of the ember out, here's some information I stole from stack overflow at some point.
var router = App.__container__.lookup("router:main"); //get the main router
var currentHandlerInfos = router.router.currentHandlerInfos; //get all handlers
var activeHandler = currentHandlerInfos[currentHandlerInfos.length - 1]; // get active handler
var activeRoute = activeHandler.handler; // active route
If you start doing controller testing, I wrote up some info on that http://discuss.emberjs.com/t/unit-testing-multiple-controllers-in-emberjs/1865

Related

Ember json search with multiple TextFields

Ember noob here. I'm basically trying to have multiple input fields for multiple parameters. As the user types into the fields, this sends off a request to a PHP script which returns the relevant JSON and displays it.
Ember 1.6.1 (latest version is a pain to learn as all of the docs are
out of date)
Handlebars 1.3.0
jQuery 1.11.1
Here's the code so far (not working for multiple).
index.html
<script type="text/x-handlebars" data-template-name="search">
{{view App.SearchTextField elementId="bedrooms" valueBinding=bedrooms upKeyAction="searchProperties" placeholder="Bedrooms"}}
{{view App.SearchTextField elementId="suburb" valueBinding=suburb upKeyAction="searchProperties" placeholder="Sydney"}}
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="search/results">
{{#each}}
<h1>{{bedrooms}} - {{street}} {{suburb}}</h1>
{{/each}}
</script>
apps.js
App = Ember.Application.create();
App.Router.map(function() {
this.resource('search', {path: '/'}, function(){
this.route('results', {path: '/search/:suburb/:bedrooms'});
});
});
App.SearchRoute = Ember.Route.extend({
actions: {
searchProperties: function(suburb, bedrooms) {
console.log(suburb);
this.transitionTo('search.results', suburb, bedrooms);
}
}
});
App.SearchResultsRoute = Ember.Route.extend({
model: function(params) {
return Ember.$.getJSON('../test/data.php?suburb='+params.suburb+'&bedrooms='+params.bedrooms);
}
});
App.SearchTextField = Ember.TextField.extend({
keyUp: function (e) {
if (e.target.id == 'bedrooms') {
var bedrooms = e.target.value;
} else if (e.target.id == 'suburb') {
var suburb = e.target.value;
}
console.log(suburb + bedrooms);
this.sendAction('action', suburb, bedrooms);
}
});
After some playing around I got it to work using this (looking more jQuery than Ember, but hey it works)
App = Ember.Application.create();
App.Router.map(function() {
this.resource('search', {path: '/'}, function(){
this.route('results', {path: '/search/:suburb/:bedrooms'});
});
});
App.SearchRoute = Ember.Route.extend({
actions: {
searchProperties: function(data) {
this.transitionTo('search.results', data.suburb, data.bedrooms);
}
}
});
App.SearchResultsRoute = Ember.Route.extend({
model: function(params) {
return Ember.$.getJSON('../test/data.php?suburb='+params.suburb+'&bedrooms='+params.bedrooms);
}
});
App.SearchTextField = Ember.TextField.extend({
keyUp: function (e) {
var data = {suburb:$('#suburb').val(), bedrooms:$('#bedrooms').val()};
this.sendAction('upKeyAction', data);
}
});
Is there a better way to do this?
You are kind of over complicating things IMO,
I'd prefer to observe for the value changes in the controller and act accordingly. Result in much reduced code, and in fact you are actually exploiting the features, the framework provides.
Sample implementation, may need to modify to fulfill your needs
App.SearchController = Ember.ObjectController.extend({
suburb : null,
bedrooms : null,
doSearch : function(){
var model = [{street: this.get('suburb'), bedrooms: this.get('bedrooms')}];
//var model = Ember.$.getJSON('../test/data.php?suburb='+this.get('suburb')+'&bedrooms='+this.get('bedrooms'));
this.transitionToRoute('search.results', model);
}.observes('suburb', 'bedrooms')
});
App.SearchRoute = Ember.Route.extend({
});
App.SearchResultsRoute = Ember.Route.extend({
});
App.SearchTextField = Ember.TextField.extend({});
FIDDLE

property in route undefined in controller

In the IndexRoute of my Ember hello world app, I start a setInterval function that I wish to allow the end user to turn off (with clearInterval) by clicking a dom element in the template, which triggers an action in the IndexController. So, the setIntervalId is set in the IndexRoute, and I need to pass it to clearInterval in the IndexController, but the way I have it below, the setIntervalId is undefined. I also tried to use App.IndexRoute.setIntervalId to no avail.
How would I accomplish this?
(function() {
window.App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_ACTIVE_GENERATION: true
});
App.IndexRoute = Ember.Route.extend({
setIntervalId: 0,
model: function() {
this.setIntervalId = setInterval(this.someInterval, 5000)
},
someInterval: function(){
var datasource = 'http://hackernews/blahblah';
return new Ember.$.ajax({url: datasource, dataType: "json", type: 'GET'}).then(function(data){
return data;
})
},
});
App.IndexController = Ember.ObjectController.extend({
actions: {
clearTimeout: function(){
console.log('clearing interval', this.setIntervalId); //undefined
clearInterval(this.setIntervalId);
}
}
})
})();
template
<script type="text/x-handlebars" data-template-name="index">>
<h1>Hi Babe</hi>
{{ outlet }}
<label {{action "clearTimeout" on="click"}}>clear timeout</label>
</script>
To set the model, you need to return the value in the route’s model function:
model: function() {
return this.setIntervalId = setInterval(this.someInterval, 5000)
}
To access the model in the controller, you need to use this.get('model').
actions: {
clearTimeout: function(){
console.log('clearing interval', this.get('model');
clearInterval(this.get('model'));
}
}

Emberjs route model with view

My app has a page where I'm using the view to display the data from other template with my view like this :
<script type="text/x-handlebars" data-template-name="enquiry">
[...] // some other information display before
{{view App.EnquirySelectedVehicleView}}
</script>
<script type="text/x-handlebars" data-template-name="selectedVehicle">
// Here is my content
</script>
My map looks like this :
this.resource('enquiry', { path: '/enquiry/:enquiry_id'}, function() {
this.route('selectedVehicle');
});
After reading the doc I just did this in my view :
App.EnquirySelectedVehicleView = Ember.View.extend({
templateName: 'selectedVehicle'
});
So far so good, its showing the text from my template. But I need to return data from an ajax call in this template (selectedVehicle) automatically, like its fetching the data when you are on /enquiry/1/.
I've done this in my router :
App.EnquirySelectedVehicle = Ember.Object.extend({});
App.EnquirySelectedVehicleRoute = Ember.Route.extend({
model: function() {
console.log('DEBUG: SelectedVehicle Model');
App.SelectedVehicle.vehicleStock(this)
}
});
App.EnquirySelectedVehicle.reopenClass({
vehicleStock: function(that) {
console.log('DEBUG: Fetch vehicle stock');
// Here come the ajax call
}
});
But my issue is that route is never call.. How can I return some value from my selectedVehicleRoute when I'm on the /enquiry/1 page in a view template ? (not sure if I ask it correctly)
Thanks for the help !
[edit]
#Fanta : I think I begin to understand how I can do that :
App.EnquiryRoute = Ember.Route.extend({
beforeModel: function(transition) {
this.controllerFor('login').send('isSession', transition);
},
model: function(param) {
var promise = new Ember.RSVP.Promise(function(resolve, reject) {
var modelData = {enquiry: {}, vehicleStock: {}};
Ember.$
.get(host + '/enquiry/' + param['enquiry_id'], function(data) {
console.log('DEBUG: Enquriry GET OK id = ' + param['enquiry_id']);
modelData.enquiry = data.enquiry;
Ember.$.get(host + '/vehiclestock/' + data.enquiry.VehicleStockId, function(data) {
console.log('DEBUG: VehicleStock GET OK id = ' + data.enquiry.VehicleStockId)
console.log(data);
modelData.vehicleStock = data.vehicleStock;
resolve(modelData);
});
});
});
return promise;
}
});
It seems to work, now I have to figure it out how to display my Object :) but thank you for your help, that actually make me resolve it by a different way !
For future reference, just go to https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md and you'll see two links, one to JSFiddle and one to a JSBin with the basic setup.
Are you sure the route is not being called ? I created a Fiddle, http://jsfiddle.net/NQKvy/817/ if you check the JS console, you'll see in the log:
DEBUG: SelectedVehicle Model
DEBUG: Fetch vehicle stock

Ember Router transitionTo nested route with params

App.Router.map(function() {
this.resource('documents', { path: '/documents' }, function() {
this.route('edit', { path: ':document_id/edit' });
});
this.resource('documentsFiltered', { path: '/documents/:type_id' }, function() {
this.route('edit', { path: ':document_id/edit' });
this.route('new');
});
});
And this controller with a subview event that basically transitions to a filtered document
App.DocumentsController = Ember.ArrayController.extend({
subview: function(context) {
Ember.run.next(this, function() {
//window.location.hash = '#/documents/'+context.id;
return this.transitionTo('documentsFiltered', context);
});
},
});
My problem is that this code works fine when Hash of page is changed.
But when I run the above code NOT w/ the location.hash bit and w/ the Ember native transitionTo I get a cryptic
Uncaught TypeError: Object [object Object] has no method 'slice'
Any clues?
Thanks
UPDATE:
App.DocumentsFilteredRoute = Ember.Route.extend({
model: function(params) {
return App.Document.find({type_id: params.type_id});
},
});
{{#collection contentBinding="documents" tagName="ul" class="content-nav"}}
<li {{action subview this}}>{{this.nameOfType}}</li>
{{/collection}}
The problem is that your model hook is returning an array, while in your transitionTo you are using a single object. As a rule of thumb your calls to transitionTo should pass the same data structure that is returned by your model hook. Following this rule of thumb i would recommend to do the following:
App.DocumentsController = Ember.ArrayController.extend({
subview: function(document) {
var documents = App.Document.find({type_id: document.get("typeId")});
Ember.run.next(this, function() {
return this.transitionTo('documentsFiltered', documents);
});
}
});
Note: I assume that the type_id is stored in the attribute typeId. Maybe you need to adapt it according to your needs.

How do you test your emberjs routes?

After a few months without looking at emberjs, I'm trying to go back into it now, and I'm therefore trying the new router. And I would like to test my routes.
Has anybody tried to write some routing tests with emberjs ?
Let's suppose the very basic following router :
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router, context) {
router.get('applicationController').connectOutlet({name: 'home'});
}
})
})
})
How do you test that loading the root.index route properly loads the HomeView ?
Here is the full test, using Jasmine & Sinon :
code:
describe("Given the Router", function(){
var router = null;
beforeEach(function(){
router = Router.create();
});
afterEach(function(){
router = null;
});
it("Should be defined", function(){
expect(router).toBeDefined();
});
it("Should have an root route", function(){
expect(router.get("root")).toBeDefined();
});
describe("its root route", function(){
var root = null;
beforeEach(function(){
root = router.get("root").create();
});
afterEach(function(){
root = null;
});
it("should have an index route", function(){
expect(root.get("index")).toBeDefined();
});
describe("its index route", function(){
var indexRoute = null;
beforeEach(function(){
indexRoute = root.get("index").create();
});
it ("should have route of /", function(){
expect(indexRoute.get("route")).toEqual("/");
});
it ("should connect the outlets to home", function(){
var fakeRouter = Em.Object.create({applicationController: {connectOutlet: function(){} } });
var connectOutletSpy = sinon.spy(fakeRouter.applicationController, "connectOutlet");
var methodCall = connectOutletSpy.withArgs({name:"home"});
indexRoute.connectOutlets(fakeRouter);
expect(methodCall.calledOnce).toBeTruthy();
});
});
});
});
Hope it helps.
Here is how Ember has already tested the connectOutlet for you:
https://github.com/emberjs/ember.js/blob/master/packages/ember-views/tests/system/controller_test.js
test("connectOutlet instantiates a view, controller, and connects them", function() {
var postController = Ember.Controller.create();
var appController = TestApp.ApplicationController.create({
controllers: { postController: postController },
namespace: { PostView: TestApp.PostView }
});
var view = appController.connectOutlet('post');
ok(view instanceof TestApp.PostView, "the view is an instance of PostView");
equal(view.get('controller'), postController, "the controller is looked up on the parent's controllers hash");
equal(appController.get('view'), view, "the app controller's view is set");
});
Other routing related tests can be found at https://github.com/emberjs/ember.js/tree/master/packages/ember-routing/tests